如何获取目录的大小?(How to get the size of a directory?)
优质
小牛编辑
127浏览
2023-12-01
问题描述 (Problem Description)
如何获取目录的大小?
解决方案 (Solution)
下面的示例演示如何借助FileUtils类的FileUtils.sizeofDirectory(File Name)方法获取目录的大小。
import java.io.File;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
System.out.println("Size: " + size + " bytes");
}
}
结果 (Result)
上面的代码示例将产生以下结果。
Size: 2048 bytes
以下是获取Java中目录大小的另一个示例示例
import java.io.File;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
long folderSize = findSize("C:\\a");
System.out.println("Size in byte :"+folderSize);
}
public static long findSize(String path) {
long totalSize = 0;
ArrayList<String> directory = new ArrayList<String>();
File file = new File(path);
if(file.isDirectory()) {
directory.add(file.getAbsolutePath());
while (directory.size() > 0) {
String folderPath = directory.get(0);
System.out.println("Size of this :"+folderPath);
directory.remove(0);
File folder = new File(folderPath);
File[] filesInFolder = folder.listFiles();
int noOfFiles = filesInFolder.length;
for(int i = 0 ; i < noOfFiles ; i++) {
File f = filesInFolder[i];
if(f.isDirectory()) {
directory.add(f.getAbsolutePath());
} else {
totalSize+=f.length();
}
}
}
} else {
totalSize = file.length();
}
return totalSize;
}
}
上面的代码示例将产生以下结果。
Size of this :C:\a
Size of this :C:\a\b
Size of this :C:\a\b\c
Size of this :C:\a\b\c\d
Size in byte :0