Java Reference
In-Depth Information
8-9. Iterating Over Files in a Directory
Problem
You need to scan files from a directory. There are possibly subdirectories with more
files. You want to include those in your scan.
Solution
Using the NIO.2, create a
FileVisitor
object and perform a desired implementa-
tion within its
visitFile
method. Next, obtain the default
FileSystem
object and
grab a reference to the
Path
that you'd like to scan via the
getPath()
method.
Lastly, invoke the
Files.walkFileTree()
method, passing the
Path
and the
FileVisitor
that you created. The following code demonstrates how to perform
these tasks.
FileVisitor<Path> myFileVisitor = new
SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs)
throws IOException {
System.out.println("Visited File:
"+file.toString());
return FileVisitResult.CONTINUE;
}
};
FileSystem fileSystem = FileSystems.getDefault();
Path directory= fileSystem.getPath(".");
try {
Files.walkFileTree(directory, myFileVisitor);
} catch (IOException e) {
e.printStackTrace();
}