Gili Gili - 2 months ago 10
Java Question

How to construct a Path from a jar:file URL?

How do I construct a

Path
to a
jar:file
URL?

Invoking
Paths.get(new URI("jar:file:/C:/foo.jar!/bar.html"))
throws
FileSystemNotFoundException
(notice the file system is missing, not the file itself).

As far as I can tell, both files exist. Any ideas?

Answer

Paths tries to resolve a FileSystem which would contain your Path. (Actually this may be an implementation detail. The spec simply states that it will check the default FileSystem.) If you haven't registered/created such a FileSystem, it won't be able to find it.

You would create a new FileSystem from the jar file and access the entry Path through that FileSystem.

Path path = Paths.get("C:/foo.jar");
URI uri = new URI("jar", path.toUri().toString(),  null);

Map<String, String> env = new HashMap<>();
env.put("create", "true");

FileSystem fileSystem = FileSystems.newFileSystem(uri, env);
Path file = fileSystem.getPath("bar.html");
System.out.println(file);

You could then use

Paths.get(new URI("jar:file:/C:/foo.jar!/bar.html"))

Be careful to properly close the FileSystem when finished using it.

For more information about ZipFileSystemProvider, see here.

Comments