Skip to content

Instantly share code, notes, and snippets.

@besza
Created December 29, 2021 22:52
Show Gist options
  • Save besza/125b9f0f6ea1be2ebdad5eeddbb99608 to your computer and use it in GitHub Desktop.
Save besza/125b9f0f6ea1be2ebdad5eeddbb99608 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class WalkFileTreeDemo {
public static void main(String[] args) throws IOException {
var startingDir = Path.of("C:", "Users", "szabolcs.z.besenyei");
var visitor = new SizeCollectorVisitor();
Files.walkFileTree(startingDir, visitor);
System.out.format("Visited: %d, Disk space: %f MB%n", visitor.visited, visitor.sum / Math.pow(1024, 2));
}
public static class SizeCollectorVisitor extends SimpleFileVisitor<Path> {
long sum = 0L;
long visited = 0L;
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file != null && attrs != null) {
++visited;
sum += attrs.size();
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
if (exc instanceof AccessDeniedException) {
System.err.println("Could not visit directory: " + file.getFileName());
return FileVisitResult.SKIP_SUBTREE;
} else if (exc instanceof NoSuchFileException) {
//System.err.println("No such file: " + file.getFileName());
return FileVisitResult.CONTINUE;
} else
return super.visitFileFailed(file, exc);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment