有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文件Java路径如何转换为例如InputStream

爪哇。尼奥。Files类有一个名为Files#newInputStream的静态方法,该方法将路径实例作为输入,并将InputStream作为输出返回。但我不清楚如何在不实例化文件(InputStream)对象的情况下实现这一点。我希望能够实现我自己的Path,它可以指向与文件对象无关的InputStream。我想这样做,这样我就可以创建一个虚拟文件系统,它使用文件系统的符号,而不依赖于文件系统。这可能吗


共 (1) 个答案

  1. # 1 楼答案

    JavaNIO文件系统API使用委托和抽象工厂模式。在最底层,是^{}的实现:

    Service-provider class for file systems. The methods defined by the Files class will typically delegate to an instance of this class. [emphasis added]

    AFileSystemProvider提供了^{}的实例:

    Provides an interface to a file system and is the factory for objects to access files and other objects in the file system.

    The default file system, obtained by invoking the FileSystems.getDefault method, provides access to the file system that is accessible to the Java virtual machine. The FileSystems class defines methods to create file systems that provide access to other types of (custom) file systems.

    A file system is the factory for several types of objects: [emphasis added]

    • The getPath method converts a system dependent path string, returning a Path object that may be used to locate and access a file.

    • The getPathMatcher method is used to create a PathMatcher that performs match operations on paths.

    • The getFileStores method returns an iterator over the underlying file-stores.

    • The getUserPrincipalLookupService method returns the UserPrincipalLookupService to lookup users or groups by name.

    • The newWatchService method creates a WatchService that may be used to watch objects for changes and events.

    然后是^{}接口:

    An object that may be used to locate a file in a file system. It will typically represent a system dependent file path.

    请注意Path只是一条路径。它不一定代表实际的文件,只代表文件的路径(无论它是否存在)。在这方面,它与java.io.File类似

    当调用Files类中的方法时,它使用^{}^{}方法来委托给FileSystemProvider。这种API设计允许开发人员以透明的方式将Files类与Path的任何实现一起使用。对开发者来说,如何创建InputStream并不重要,只是InputStream是以符合API合同的方式创建的

    方法^{}^{}委托给default file system来创建Path的实例。当您将这些Path实例与Files中的方法一起使用时,您最终会访问主机平台的底层文件系统

    如果你想创建一个虚拟文件系统,那么你需要实现一个FileSystemProvider以及所有相关的抽象类和接口,比如FileSystemPath。不过请注意,有些API是“可选的”。如果您的实现没有提供可选的API,那么您可以抛出一个UnsupportedOperationException。各种类/方法的Javadoc提供了更多信息

    也就是说,已经有了一个内存中的文件系统实现:https://github.com/google/jimfs


    但我不清楚如何在不实例化文件(InputStream)的情况下实现这一点。”。NIO文件API与java.io.File无关。如果你想看看它是怎么做到的,你可以看看源代码。您的JDK应该附带一个src.zip文件,其中包含Java源文件;但是,它只包含主机操作系统的实现,不包含任何本机代码(默认文件系统最终使用本机代码与底层操作系统的文件系统通信)