Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NIO.2 FileVisitor type generic?

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 IOExceptions.

So, were there any reasons for parameterizing FileVisitor type?

like image 790
Vladimir Matveev Avatar asked May 06 '13 20:05

Vladimir Matveev


2 Answers

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);
    }
}
like image 74
nosid Avatar answered Nov 18 '22 19:11

nosid


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.

like image 5
OldCurmudgeon Avatar answered Nov 18 '22 17:11

OldCurmudgeon