I'm doing some research on Java NIO.2 and its file operations, and currently I'm playing with filetree-walking functions and classes.
NIO.2 FileVisitor
API is wonderful, it's a shame that such thing has been added to Java SE only recently, not ten years ago. However, there is something which slightly bothers me: what is the point of making FileVisitor
interface generic?
Every single example on the net shows how to use it with Files.walkFileTree()
which implies that we are using FileVisitor<Path>
type. But I just cannot see any use for this interface for things other than Path
. Well, it may be possible to use FileVisitor
to walk other kinds of trees (in-memory ones?), but this just doesn't feel right: this interface and related classes have very specific names semantically tied to files, and also FileVisitor
's methods throw IOException
s.
So, were there any reasons for parameterizing FileVisitor
type?
With generics the same interface can be used for other types of paths. As shown in the following (simplified) code fragment, the interface works nice with java.io.File
:
FileVisitResult walk(File file, FileVisitor<File> visitor)
throws IOException
{
if (file.isDirectory()) {
visitor.preVisitDirectory(file, null);
for (File child : file.listFiles()) {
walk(child, visitor);
}
return visitor.postVisitDirectory(file, null);
} else {
return visitor.visitFile(file, null);
}
}
Do you use GitHub? This would be a perfect opportunity to use the FileVisitor
to implement an API to GitHub that allows you to explore/visualise GitHub projects. For that matter almost any SCC system could make use of a different class as the file locator
And how about using a FileVisitor<ZipEntry>
for traversing zip files.
If an API is potentially usable with multiple objects as its target it just makes sense to make it generic. I think not making it generic would be the mistake that should be considered foolish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With