By java how to count file numbers in a directory without list()

浪尽此生 提交于 2019-12-25 04:21:31

问题


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.



来源:https://stackoverflow.com/questions/39715607/by-java-how-to-count-file-numbers-in-a-directory-without-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!