Gili Gili - 7 months ago 44
Java Question

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

How do I construct a

to a

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

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


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");

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.