问题
如何在Java中检索文件夹或文件的大小?
#1 热门回答(167 赞)
java.io.File file = new java.io.File("myfile.txt");
file.length();
如果文件不存在,则返回文件的长度(以字节为单位)或0
。没有内置的方法来获取文件夹的大小,你将不得不递归地遍历目录树(使用表示目录的文件对象的listFiles()
方法)并为你自己累积目录大小:
public static long folderSize(File directory) {
long length = 0;
for (File file : directory.listFiles()) {
if (file.isFile())
length += file.length();
else
length += folderSize(file);
}
return length;
}
警告:此方法对于生产用途而言不够稳健.directory.listFiles()
可能返回null
并导致aNullPointerException
。此外,它不考虑符号链接,可能还有其他失败模式。 Usethis method。
#2 热门回答(34 赞)
你需要FileUtils#sizeOfDirectory(File)
来自commons-io。
请注意,你需要手动检查文件是否是目录,因为如果向其传递非目录,该方法将引发异常。
警告:此方法(从commons-io 2.4开始)有一个错误,如果同时修改了该目录,则可能会抛出IllegalArgumentException
。
#3 热门回答(33 赞)
使用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();
}