By java how to count file numbers in a directory w

2019-09-11 19:09发布

问题:

Without using file.list() or Files.list(path), how to count file numbers in a directory?

I just want a number, no detail. Given me a quick way please.

回答1:

If your only concern is to not create a List<File> you might use the Stream API.

long count = Files.list(Paths.get(path))
        .filter(p -> p.toFile().isFile())
        .count();
System.out.println("count = " + count);

edit The snippet is not meant to be fast. It was only provied for the requirement not to use list() or listFiles(). ;-)

Following a small comparison of different ways of counting the number of files in a directory containing two million files.

All commands are executed twice. First execution is with dropped file cache and the second execution followed right after the first one.

              | ls    | dir.list() | dir.listFiles() | Files.list(path)
--------------+-------+------------+-----------------+------------------
dropped cache | 9,120 |   5,518    |      5,879      |      59,175
filled cache  |   946 |   1,992    |      2,401      |      51,179      

times in milliseconds (the comma is the thousands separator)

Below the executed commands in detail.

ls

ls -f /tmp/huge-dir | wc -l

dir.list()

File hugeDir = new File("/tmp/huge-dir");
int numberFiles = hugeDir.list().length;

dir.listFile()

File hugeDir = new File("/tmp/huge-dir");
int numberFiles = hugeDir.listFiles().length;

Files.list(path)

Path path = Paths.get("/tmp/huge-dir");
long numberFiles = Files.list(path)
        .filter(p -> p.toFile().isFile())
        .count();

Based on those figures. Using dir.list().length seems to be not a bad solution.



标签: java java-io