Search code examples
javaurlfilesystemsprotocolsapache-commons-vfs

Commons VFS and Java.net.URL - Adding support for “ram://” protocol


I'm using commons-vfs and for my tests I want to use a ram file system. When I try with new URL("ram:///A/B/sample.jar") I get the following exception:

java.net.MalformedURLException: unknown protocol: ram
    at java.net.URL.<init>(URL.java:592)
    at java.net.URL.<init>(URL.java:482)
    at java.net.URL.<init>(URL.java:431)

Here is some code (when I use file protocol everything works fine)

// URL is used to construct an object
obj.addArchive(new URL("ram:///A/B/sample.jar"))    
...
// then VFS is used to scan the object urls
// for instance get the parent directory
FileSystemManager manager = VFS.getManager();
String directory = manager.resolveFile(obj.getPath()).getParent().getURL().toExternalForm();

How I could use ram protocol in java.net.URL?


Solution

  • VFS supports creating a stream handler factory which knows about all the registered schemes.

    // you might want to configure a manager with less schemes
    FileSystemManager fsm = VFS.getManager(); 
    URLStreamHandlerFactory factory = fsm.getURLStreamHandlerFactory();
    URL.setURLStreamHandlerFactory(factory); // VM global
    URL url = new URL("ram://test.txt");