user3629892
user3629892

Reputation: 3046

creating virtual file system with apache VFS

For unit tests, I'd like to create an in-memory file system with VFS.

My current code:

final String ROOTPATH = "ram://virtual";

        FileSystemManager fsManager = VFS.getManager();
        fsManager.createVirtualFileSystem(ROOTPATH);
        FileObject testFile = fsManager.resolveFile(ROOTPATH + "/test.txt");
        testFile.createFile();

        FileObject testFile2 = fsManager.resolveFile(ROOTPATH + "/test2.txt");
        testFile2.createFile();

        FileObject testFile3 = fsManager.resolveFile(ROOTPATH + "/test3.txt");
        testFile3.createFile();

        FileObject testFile4 = fsManager.resolveFile(ROOTPATH + "/test4.txt");
        testFile4.createFile();

        FileObject folder = fsManager.resolveFile(ROOTPATH);
        FileObject[] files = folder.getChildren();
        for (FileObject file : files) {
            System.out.println(file.getName());
        }

My question: Is this the correct way to do it? Examples on this topica are sparse.

I still get the log message:

Apr 14, 2015 11:08:17 AM org.apache.commons.vfs2.VfsLog info
INFORMATION: Using "/tmp/vfs_cache" as temporary files store.

Can I ignore this, since I am using the ram URI scheme? I guess it's because I didn't configure the DefaultFileSystemManager.

Thanks for help and tips!

EDIT:

Now with the marschall memoryFileSystem:

I copied the example code from their website.

This is my @Test-Method:

FileSystem fileSystem = this.rule.getFileSystem();

Path testDirectoryPath  = Paths.get("test");
Files.createDirectories(testDirectoryPath);
Path p = fileSystem.getPath("test");
System.out.println(p.getFileName());
System.out.println(p.getFileSystem());

Path testfile = Paths.get("test/text2.txt");
Path test = Files.createFile(testfile);
Path f = fileSystem.getPath("test/text2.txt");
System.out.println(f.getFileName());
System.out.println(f.getFileSystem());
System.out.println(f.toAbsolutePath());

This is the console output:

test
MemoryFileSystem[VirtualTestFileSystem]
text2.txt
MemoryFileSystem[VirtualTestFileSystem]
/test/text2.txt

Looks alright, however: The files and directories actually get created on my hard drive, in the project folder. I thought, the whole point of this was to avoid exactly that...? Am I doing something wrong or do I just not get it...?

Upvotes: 4

Views: 4063

Answers (1)

Philippe Marschall
Philippe Marschall

Reputation: 4604

Your are using Paths.get

Path testDirectoryPath  = Paths.get("test");

Paths.get always creates paths on the default file system. You should use

Path testDirectoryPath  =  fileSystem.getPath("test");

Upvotes: 2

Related Questions