使用 Apache Commons VFS RAM 文件以避免将文件系统与需要文件的 API 一起使用



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

如何在内存中创建新的java.io.File?

其中 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 的文件对象转换为文件。

但是有一种方法可以让你的API也可以与InputStream一起使用。大多数库通常具有接收输入流的重载方法。在这种情况下,以下内容应该有效:

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

最新更新