Java 使用ApacheCommons VFS RAM文件避免使用API需要文件的文件系统

Java 使用ApacheCommons VFS RAM文件避免使用API需要文件的文件系统,java,apache-commons-vfs,Java,Apache Commons Vfs,在这篇帖子上有一条被高度评价的评论: Sorin Postelnicu提到使用Apache Commons VFS RAM文件作为一种方式,将内存中的文件传递给需要java.io.file的API(我正在解释……我希望我没有错过要点) 通过阅读相关文章,我得出了以下示例代码: @Test public void working () throws IOException { DefaultFileSystemManager manager = new Defa

在这篇帖子上有一条被高度评价的评论:

Sorin Postelnicu提到使用Apache Commons VFS RAM文件作为一种方式,将内存中的文件传递给需要java.io.file的API(我正在解释……我希望我没有错过要点)

通过阅读相关文章,我得出了以下示例代码:

    @Test
    public void working () throws IOException {

        DefaultFileSystemManager manager = new DefaultFileSystemManager();
        manager.addProvider("ram", new RamFileProvider());
        manager.init();
        final String rootPath = "ram://virtual";
        manager.createVirtualFileSystem(rootPath);

        String hello = "Hello, World!";
        FileObject testFile = manager.resolveFile(rootPath + "/test.txt");
        testFile.createFile();

        OutputStream os = testFile.getContent().getOutputStream();

        os.write(hello.getBytes());
        //FileContent test = testFile.getContent();

        testFile.close();

        manager.close();

    }
所以,我想我有一个内存文件叫做ram://virtual/test.txt 内容为“你好,世界!”


我的问题是:如何将此文件与需要java.io.file的API结合使用?

java的文件API始终与本机文件系统配合使用。因此,如果本机文件系统上没有文件,就无法将VFS的FileObject转换为File

但是,如果您的API也可以使用InputStream,那么有一种方法。大多数库通常都有重载方法来接收InputStreams。在这种情况下,应采取以下措施:

InputStream is = testFile.getContent().getInputStream();
SampleAPI api = new SampleApi(is);