java上一级目录,访问目录的第一级并获取每个目录Java的大小

I need the list of the directories in the C: And get size for each one.

I am trying with this code:

int[] count = {0};

try {

Files.walkFileTree(Paths.get(dir.getPath()), new HashSet(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),

Integer.MAX_VALUE, new SimpleFileVisitor() {

@Override

public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {

System.out.printf("Visiting file %s\n", file);

++count[0];

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {

System.err.printf("Visiting failed for %s\n", file);

return FileVisitResult.SKIP_SUBTREE;

}

@Override

public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {

System.out.printf("About to visit directory %s\n", dir);

return FileVisitResult.CONTINUE;

}

});

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

The problem I have is that if I use exactly this, Takes a lot of time because it visits each file! of the disk. I tried with differents options for FileVisitResult but I can't get the desired result. I need only first level with space in the disk.

Thanks in advance for any help.

解决方案

Folders do not have a (significant) size of their own. Usually when a folder size is discussed, the meaning is the sum of sizes of all files under that folder and its sub-folders. This operation takes a "very long" time for C:\ (try right-clicking your Program Files folder and hitting properties). Remove all logs and try again. Compare the time it took your code, with the time it takes Windows Explorer to calculate that size (again, by right-clicking your Program Files folder and hitting properties).

In any case, Apache's commons-io has a one-liner:

long size = FileUtils.sizeOfDirectory(folder);

And Java-8 has another "pure" one-liner:

long size = Files.walk(Paths.get("C:\\"))

.filter(p -> p.toFile().isFile())

.mapToLong(p -> p.toFile().length())

.sum();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值