簡體   English   中英

使用 Apache Commons VFS RAM 文件以避免使用需要文件的 API 文件系統

[英]Use Apache Commons VFS RAM file to avoid using file system with API requiring a file

這篇文章有一個高度贊成的評論:

如何在 memory 中創建新的 java.io.File?

where Sorin Postelnicu mentions using an Apache Commons VFS RAM file as a way to have an in memory file to pass to an API that requires a java.io.File (I am paraphrasing... I hope I haven't missed the point) .

根據閱讀相關文章,我想出了這個示例代碼:

    @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();

    }

所以,我認為我在 memory 中有一個名為 ram://virtual/test.txt 的文件,其內容為“Hello, World!”

我的問題是:如何將此文件與需要 java.io.File 的 API 一起使用?

Java 的文件 API 始終適用於本機文件系統。 因此,如果文件不存在於本機文件系統上,就無法將 VFS 的 FileObject 轉換為 File。

但是如果您的 API 也可以與 InputStream 一起使用,那么有一種方法。 大多數庫通常具有接收 InputStreams 的重載方法。 在這種情況下,以下應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM