结果
上面的代码示例将产生以下结果。
以下是在 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