Search code examples
javajarfilesystemsnionio2

NIO's Filesystems and Paths inconsistent about default FileSystem


I am creating a FileSystem to browse the jar in case the access to my reosurces is frim within a jar.

Then I noticed that when creating a new FileSystem, it actually registers as the default file system when using Paths NIO class.

But Filesystems.getDefaultSystem keeps returning the hard disk regular one.

Why is this behaviour inconsistent and so transparent? How can I ask for the Filesystem that Paths is actually using when asked for a relative path as myResources/myResource.txt?

  System.out.println("Default FS: "+FileSystems.getDefault().getClass().getName());

  URI rscURI = Test.class.getClassLoader().getResource("folder").toURI();

  try{ Paths.get(clURI).getFileSystem(); } 
  catch(FileSystemNotFoundException e){
        System.out.println("A new Filesystem for "+clURI.getScheme()+" scheme is created.");
        FileSystems.newFileSystem(clURI, Collections.emptyMap());
        System.out.println("Default FS: "+FileSystems.getDefault().getClass().getName());

 }
 return Paths.get(rscURI)

Solution

  • You got the gist of it in your answer; Paths.get() with string arguments is in fact strictly equivalent to FileSystems.getDefault().getPath() with the same string arguments.

    Now, as to URIs, it depends on the registered file system providers, and the default filesystem provider always has scheme file. The zip filesystem provider has scheme jar.

    Now, if you specify a URI for a registered provider, the provider may, or may not, create the filesystem for you automatically.

    Do note however that FileSystem implements Closeable, therefore AutoCloseable; it is therefore recommended that you get a hold of it, and get paths from it, so that you can correctly close it when you're done with it. If you don't, you may leak resources!