如何在 Java 中检索文件夹或文件的大小?
原文由 oneat 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 java-7 nio api,可以更快地计算文件夹大小。
这是一个准备运行的示例,它很健壮并且不会抛出异常。它将记录它无法进入或无法遍历的目录。符号链接被忽略,目录的并发修改不会造成不必要的麻烦。
/**
* Attempts to calculate the size of a file or directory.
*
* <p>
* Since the operation is non-atomic, the returned value may be inaccurate.
* However, this method is quick and does its best.
*/
public static long size(Path path) {
final AtomicLong size = new AtomicLong(0);
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
size.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.out.println("skipped: " + file + " (" + exc + ")");
// Skip folders that can't be traversed
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
if (exc != null)
System.out.println("had trouble traversing: " + dir + " (" + exc + ")");
// Ignore errors traversing a folder
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new AssertionError("walkFileTree will not throw IOException if the FileVisitor does not");
}
return size.get();
}
原文由 Aksel Willgert 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.3k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
1 回答2.1k 阅读✓ 已解决
这将返回文件的字节长度或
0
如果文件不存在。没有获取文件夹大小的内置方法,您将不得不递归地遍历目录树(使用代表目录的文件对象的listFiles()
方法)并累积目录适合自己的尺码:警告:此方法对于生产使用而言不够稳健。
directory.listFiles()
可能返回null
并导致NullPointerException
。此外,它不考虑符号链接并且可能有其他故障模式。使用 此方法。