java获取list序号,通过Java如何计算没有list()的目录中的文件编号

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.

解决方案

If your only concern is to not create a List 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值