Whimusical
Whimusical

Reputation: 6629

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)

Upvotes: 0

Views: 771

Answers (2)

fge
fge

Reputation: 121710

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!

Upvotes: 1

Whimusical
Whimusical

Reputation: 6629

Ok, sorry I got it.

Paths.get(URI) and Paths.get(strPath) have different mechanics. The first one loads unequivocally the specific FS, while the second one uses always getDefault() which seems to be always the disk regular one.

So if were using Paths.get(strPath) then behaviour would be as I was expecting, returning always a reference to disk's file system, coherent with getDefaultFilesystem(), no matter what you registered before,.

Upvotes: 0

Related Questions