获取目录及其子目录中的文件数

jee*_*wat 11 java android

使用此代码

new File("/mnt/sdcard/folder").listFiles().length
Run Code Online (Sandbox Code Playgroud)

返回特定目录中的文件夹和文件的总和,而不关心子目录.我想获取目录及其子目录中所有文件的数量.

PS:如果它返回所有文件和文件夹的总和几乎不重要.

任何帮助表示感谢,谢谢

小智 31

试试这个.

int count = 0;
getFile("/mnt/sdcard/folder/");

private void getFile(String dirPath) {
    File f = new File(dirPath);
    File[] files = f.listFiles();

    if (files != null)
    for (int i = 0; i < files.length; i++) {
        count++;
        File file = files[i];

        if (file.isDirectory()) {   
             getFile(file.getAbsolutePath()); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它可能会帮助你.


new*_*rld 18

你可以使用递归.

public static int getFilesCount(File file) {
  File[] files = file.listFiles();
  int count = 0;
  for (File f : files)
    if (f.isDirectory())
      count += getFilesCount(f);
    else
      count++;

  return count;
}
Run Code Online (Sandbox Code Playgroud)


Mad*_*sen 13

使用Java 8 NIO:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Test {

  public long fileCount(Path dir) { 
    return Files.walk(dir)
                .parallel()
                .filter(p -> !p.toFile().isDirectory())
                .count();
  }

  public void main(String... args) {
    Path dir = Paths.get(args[0]);
    long count = fileCount(dir);

    System.out.println(args[0] + " has " + count + " files");
  }

}
Run Code Online (Sandbox Code Playgroud)


Gre*_*nsy 7

public Integer countFiles(File folder, Integer count) {
    File[] files = folder.listFiles();
    for (File file: files) {
        if (file.isFile()) {
            count++;
        } else {
            countFiles(file, count);
        }
    }

    return count;
}
Run Code Online (Sandbox Code Playgroud)

用法:

Integer count = countFiles(new File("your/path"), Integer.valuOf(0));
Run Code Online (Sandbox Code Playgroud)