3 回答
杨__羊羊
TA贡献1943条经验 获得超7个赞
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并引起NullPointerException。此外,它不考虑符号链接,可能还有其他失败模式。使用此方法。
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
使用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();}
繁星coding
TA贡献1797条经验 获得超4个赞
你需要FileUtils#sizeOfDirectory(File)从commons-io。
请注意,您需要手动检查文件是否是目录,因为如果向其传递非目录,该方法将引发异常。
警告:此方法(从commons-io 2.4开始)有一个错误,IllegalArgumentException如果同时修改目录,则可能抛出该错误。
添加回答
举报
0/150
提交
取消
