2

I am using Java 8 to write an application that interacts with the file-system. To make testing easier, I am injecting a FileSystem into my methods, which can be swapped-out for testing. I am currently using jimfs in my unit-tests and DefaultFileSystem.getFileSystem() in production.

I would like my code to be platform independent and portable between unit-tests and production, however, I think that the classes in the standard library may prevent this.

For example, java.io.File contains this:

private static final FileSystem fs = DefaultFileSystem.getFileSystem();

It seems that File will always refer to real files, which is a problem for my unit-tests.

Path, on the other hand, is just an interface, which should make things easy, except it has a method to create a File!

File toFile();
  • Which Java classes are tied to the real file-system?
  • What are my options for writing Filesystem portable code?
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 1
    The java classes tied to the real file system are the implementations of Path provided by the jre and are environment-dependent. – Jeremy Grand Apr 04 '17 at 16:02
  • Does seem really odd that `File` seems to point at `WinNTFileSystem` always? Which seems to have changed in Java 8. – BrendanM Apr 04 '17 at 16:03
  • `Path`s [doc](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#toFile--) states that `toFile` throws an exception when the path is not tied to the default provider. It seems that this method is optional when implementing it yourself. – Jorn Vernee Apr 04 '17 at 16:04
  • @JornVernee Interesting! Unfortunately many libraries (e.g. Guava) take `File` rather than a Filesystem-independent alternative (e.g. stream). – sdgfsdh Apr 04 '17 at 16:05
  • I'm sorry I don't have time to post an actual answer now, but you should look at the javadoc of `java.nio.file.spi.FileSystemProvider`, that should be a good start – Jeremy Grand Apr 04 '17 at 16:05
  • 1
    Still seems to me that the Java design of the `File` class is odd...surly there should be a constructor to create a file for a different `FileSystem`. And interestingly in Java 7 the default was acquired using a native method `public static native FileSystem getFileSystem();` – BrendanM Apr 04 '17 at 16:10

0 Answers0