I need the list of the directories in the C: And get size for each one.
I am trying with this code:
int[] count = {0};
try {
Files.walkFileTree(Paths.get(dir.getPath()), new HashSet(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
Integer.MAX_VALUE, new SimpleFileVisitor() {
@Override
public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
System.out.printf("Visiting file %s\n", file);
++count[0];
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
System.err.printf("Visiting failed for %s\n", file);
return FileVisitResult.SKIP_SUBTREE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
System.out.printf("About to visit directory %s\n", dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem I have is that if I use exactly this, Takes a lot of time because it visits each file! of the disk. I tried with differents options for FileVisitResult but I can't get the desired result. I need only first level with space in the disk.
Thanks in advance for any help.
解决方案
Folders do not have a (significant) size of their own. Usually when a folder size is discussed, the meaning is the sum of sizes of all files under that folder and its sub-folders. This operation takes a "very long" time for C:\ (try right-clicking your Program Files folder and hitting properties). Remove all logs and try again. Compare the time it took your code, with the time it takes Windows Explorer to calculate that size (again, by right-clicking your Program Files folder and hitting properties).
In any case, Apache's commons-io has a one-liner:
long size = FileUtils.sizeOfDirectory(folder);
And Java-8 has another "pure" one-liner:
long size = Files.walk(Paths.get("C:\\"))
.filter(p -> p.toFile().isFile())
.mapToLong(p -> p.toFile().length())
.sum();