为什么使用 java 和 'du -sk' 为目录计算的已用空间是不同的?,'du -sk' 的确切 java 替代方案是什么?
PFB Java 代码,
final String location = "/home/bhlabhla";
final Path path = Paths.get(location);
final Process process = Runtime.getRuntime().exec("du -sk " + location);
final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
System.out.println("used space [du -sk]");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("***************************");
// 1
System.out.println("used space [Recursion]:" + getFolderSize(new File(location)) / 1024);
// 2
final long size = Files.walk(path).mapToLong(p -> p.toFile().length()).sum();
System.out.println("used space [Java 8]:" + size / 1024);
public static long getFolderSize(final File dir) {
long size = 0;
for (final File file : dir.listFiles()) {
if (file.isFile()) {
size += file.length();
} else {
size += getFolderSize(file);
}
}
return size;
}
输出,
已用空间 [du -sk]
83164000 /home/bhlabhla
已用空间 [递归]:83151664
已用空间 [Java 8]:83153560