Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

uri

jar

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?

like image 652
Gili Avatar asked Aug 20 '14 04:08

Gili


1 Answers

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.

like image 159
Sotirios Delimanolis Avatar answered Sep 24 '22 14:09

Sotirios Delimanolis