如何在内存中创建目录?伪文件系统/虚拟目录
对于我的用例,我希望有一个内存目录来在很短的时间内存储一些文件。实际上,我在运行时将源代码编译为 .class 文件,类加载并执行它们。干净的方法是创建一个虚拟目录并让编译器在那里创建 .class 文件。当然,我可以使用临时目录,但我必须在编译之前清理它,我不知道我是否是唯一使用它的人,等等。
所以,是以及如何可能在Java中创建一个虚拟的(内存中的)目录?
For my usecase, I would like to have an in memory directory to store some files for a very short time. Actually I compile source code to .class
files at runtime, classload and execute them. The clean way would be to create a virtual directory and let the compiler create .class files there. Of course I could use a temp directory, but I have to clean it before compiling, I don't know if I'm the only one using it, etc.
So, is and how is it possible to create a virtual, in the meaning of in memory, directory in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Java 6 中,实际上不可能在 Java 应用程序中执行此类操作。您需要依赖操作系统平台来提供伪文件系统。
在 Java 7 中,NIO API 已得到扩展,提供了允许您定义新文件系统的 API;请参阅
FileSystemProvider
。Apache Commons VFS 是另一种选择,但它有一些可能导致问题的特征对于现有代码和(第 3 方)库:
VFS 中的文件和目录使用 url 命名,而不是
File
对象。因此,使用File
进行文件操作的代码将无法工作。FileInputStream
、FileOutputStream
、FileReader
和FileWriter
无法与 VFS 一起使用。In Java 6 it is not really possible to do this kind of thing within a Java application. You need to rely on the OS platform to provide the the pseudo-filesystem.
In Java 7, the NIO APIs have been extended to provide an API that allows you to define new file systems; see
FileSystemProvider
.Apache Commons VFS is another option, but it has a couple of characteristics that may cause problems for existing code and (3rd-party) libraries:
Files and directories in VFS are named using urls, not
File
objects. So code that usesFile
for file manipulation won't work.FileInputStream
,FileOutputStream
,FileReader
andFileWriter
won't work with VFS for much the same reason.听起来你可以使用虚拟磁盘。有很多应用程序可以执行此操作,您使用的应用程序取决于目标操作系统。我不知道有任何本机 Java API 支持此功能。
It sounds like you could use a ramdisk. There are many apps out there that will do this, what you use would depend on the target OS. I don't know of any native Java API that supports this.
我不确定这是否有帮助,但请检查 Apache Commons VFS。
看来你需要的是内存文件系统。
I am not sure if this is helpful or not, but do check Apache Commons VFS.
It seems that what you need is memory filesystem.
对于 Java7 的 NIO 有
For Java7's NIO there are
我使用 jimfs by Google 作为内存文件系统。
看起来这就是这里所需要的。
对于与文件系统交互的单元/集成测试应用程序来说,它也非常好。
I've used jimfs by Google as an in memory file system.
It looks like that would be what's needed here.
It's also very nice for unit/integration testing applications that interact with the filesystem.