Can a java RAM disk be created to be used with the java.io.* API?

Tomislav Nakic-Alfirevic picture Tomislav Nakic-Alfirevic · Dec 13, 2010 · Viewed 7.4k times · Source

I'm using a 3rd party library which basically creates an output directory with different kinds of files and subdirectories inside. I would like to be able to write unit tests to confirm that the output is correct.

I would like to be able to use the lib with a RAM disk, so that nothing the library does touches actual disk plates in any way. The idea is to make the tests very fast to run and clean up (drop RAM disk?).

The two most prominent options available to me are Commons VFS and JSR 203. The former is of no use to me because I want things to work transparently using the java.io.* API and not Commons VFS classes. The later doesn't cut it because I have to make do with JDK 6 (it's supposed to be a part of JDK 7) and I don't know if it will work seamlessly with java.io.* anyway (I wouldn't bet on it).

There are other solutions as well, but I can't use them for the same reason I can't use Commons VFS. Mocks are out of the question because of the complexity of the library in question.

On my linux machine, I can easily create a RAM drive and use the java.io.* API the same way I would with files on disk. The thing is, I want it to be cross-platform and more specifically, to make disk setup a part of the test procedure, rather than something external.

So, is there a way to register a RAM drive in Java which would be usable with the standard java.io.* API?

Answer

Stephen C picture Stephen C · Dec 13, 2010

So, is there a way to register a RAM drive in Java which would be usable with the standard java.io.* API?

Not with a Java 6 or earlier JVM. Java 6 and earlier do not provide any SPI for registering file systems or file system types. So, to implement a RAM FS that an application would use like a normal FS would entail modifying the behavior of a number of java.io.* classes.

I think that the best thing that you could do would be to use a RAM FS implemented by the host operating system. You should be able to access that from Java as if it was a normal file system. However, I/O would entail a system calls, so it wouldn't be as fast as if the RAM file system was held in the JVM managed memory.