get number of files in a directory and its subdirectories

后端 未结 12 877
猫巷女王i
猫巷女王i 2020-12-28 09:19

using this code

new File(\"/mnt/sdcard/folder\").listFiles().length

returns a sum of folders and files in a particular directory without ca

12条回答
  •  借酒劲吻你
    2020-12-28 10:13

    Using 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");
      }
    
    }
    

提交回复
热议问题