【发布时间】: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 一起使用?
【问题讨论】: