本文介绍了通过Java如何计算没有list()的目录中的文件编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不使用file.list()Files.list(path),如何计算目录中的文件编号?

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.

推荐答案

如果仅考虑不创建List<File>,则可以使用Stream API.

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);

编辑这段代码并不意味着很快.仅提供了不使用list()listFiles()的要求. ;-)

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

下面是对包含200万个文件的目录中文件数量进行计数的不同方式的比较.

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 = Paths.get("/tmp/huge-dir");
long numberFiles = Files.list(path)
        .filter(p -> p.toFile().isFile())
        .count();

基于这些数字.使用dir.list().length似乎不是一个糟糕的解决方案.

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

这篇关于通过Java如何计算没有list()的目录中的文件编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:14