【问题标题】:Use Apache Commons VFS RAM file to avoid using file system with API requiring a file使用 Apache Commons VFS RAM 文件来避免使用需要文件的 API 的文件系统
【发布时间】:2020-01-28 03:31:49
【问题描述】:

这篇文章有一个高度赞成的评论:

how to create new java.io.File in memory?

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 的内存文件,内容为“Hello, World!”

我的问题是:如何将此文件与需要 java.io.File 的 API 一起使用?

【问题讨论】:

    标签: java apache-commons-vfs


    【解决方案1】:

    Java 的文件 API 始终适用于本机文件系统。因此,如果文件不存在于本机文件系统上,就无法将 VFS 的 FileObject 转换为 File。

    但是如果您的 API 也可以与 InputStream 一起使用,则有一种方法。大多数库通常具有接收 InputStreams 的重载方法。在这种情况下,以下应该可以工作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多