Search code examples
javaapache-commons-vfs

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


There is a highly upvoted comment on this post:

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

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).

Based on reading related posts I have come up with this sample code:

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

    }

So, I think that I have an in memory file called ram://virtual/test.txt with contents "Hello, World!"

My question is: how could I use this file with an API that requires a java.io.File?


Solution

  • Java's File API always works with native file system. So there is no way of converting the VFS's FileObject to File without having the file present on the native file system.

    But there is a way if your API can also work with InputStream. Most libraries usually have overloaded methods that take in InputStreams. In that case, following should work:

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