简体   繁体   English

为什么NIO.2 FileVisitor类型是通用的?

[英]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. 我正在研究Java NIO.2及其文件操作,目前我正在使用filetree-walking函数和类。

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. NIO.2 FileVisitor API很棒,很遗憾,最近才在Java SE中添加了这样的东西,而不是十年前。 However, there is something which slightly bothers me: what is the point of making FileVisitor interface generic? 但是,有些东西让我感到困扰:使FileVisitor接口通用的重点是什么?

Every single example on the net shows how to use it with Files.walkFileTree() which implies that we are using FileVisitor<Path> type. 网上的每个例子都显示了如何将它与Files.walkFileTree()一起使用,这意味着我们正在使用FileVisitor<Path>类型。 But I just cannot see any use for this interface for things other than Path . 但我只是看不到除了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. 那么,有可能使用FileVisitor来处理其他种类的树(内存中的那些?),但这感觉不对:这个接口和相关的类具有语义上与文件绑定的非常具体的名称,还有FileVisitor '方法抛出IOException

So, were there any reasons for parameterizing FileVisitor type? 那么,有没有理由参数化FileVisitor类型?

Do you use GitHub ? 你用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. 这将是一个使用FileVisitor实现GitHub API的绝佳机会,它允许您探索/可视化GitHub项目。 For that matter almost any SCC system could make use of a different class as the file locator 就此而言,几乎任何SCC系统都可以使用不同的类作为文件定位器

And how about using a FileVisitor<ZipEntry> for traversing zip files. 如何使用FileVisitor<ZipEntry>来遍历zip文件。

If an API is potentially usable with multiple objects as its target it just makes sense to make it generic. 如果API可能与多个对象一起使用作为其目标,那么将其设置为通用是有意义的。 I think not making it generic would be the mistake that should be considered foolish. 我认为不要把它变成一般是错误应该被认为是愚蠢的。

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 : 如下面的(简化的)代码片段所示,该接口适用于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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM