0
對於給定的目錄,我試圖遞歸檢索每個目錄的大小(以最有效的方式)。如果可能的話,我想使用Java8 NIO Streams(速度爲&效率),但是會與第三方庫(爲什麼重新發明輪子)解決。Java8 NIO Stream>更有效地遞歸檢索目錄大小的方法?
例如,在遍歷每個級別時遍歷深度優先目錄,總結子文件/預先計算目錄大小會更有效。我目前的解決方案效率低下,因爲它從頂層開始重新計算目錄大小。
任何建議庫/代碼示例/指導,將不勝感激...
目前的解決方案:
import java.io.IOException;
import java.nio.file.*;
import java.util.Map;
import static java.util.stream.Collectors.toMap;
public class DirectorySizes {
public static void main(String[] args) throws IOException {
// retrieve map of path -> size...
Map<Path, Long> directorySize = Files.walk(Paths.get("/tmp"))
.filter(Files::isDirectory)
.collect(toMap(Path::toAbsolutePath, DirectorySizes::getDirectorySize));
// print {size} {directory}...
directorySize.entrySet().forEach(e ->
System.out.printf("%15s %s %n", e.getValue(), e.getKey())
);
}
public static long getDirectorySize(Path path) {
try {
return Files.walk(path).filter(Files::isRegularFile)
.mapToLong(DirectorySizes::getFileSize).sum();
} catch (IOException e) {
return 0;
}
}
public static long getFileSize(Path file) {
try {
return Files.size(file);
} catch (IOException e) {
return 0;
}
}
}
輸出示例:
2812 C:\tmp\foobar\static\css
6936 C:\tmp\foobar\static
7821 C:\tmp\foobar