Created
December 29, 2021 22:52
-
-
Save besza/125b9f0f6ea1be2ebdad5eeddbb99608 to your computer and use it in GitHub Desktop.
Practical NIO with Ben Evans: https://blogs.oracle.com/javamagazine/post/java-path-nio2-directory-extensions-zip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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