Thomas S.
Thomas S.

Reputation: 6335

Java - find jar file of class (or classes directory)

I can request the URL for the jar file or classes directory where Java loaded a class from:

Class clazz = ...
URL url = clazz.getProtectionDomain().getCodeSource().getLocation();

but how to correctly convert this to a File (or Path) - especially with respect to some characters of the path escaped in URLs? I've tried this:

String fileName = URLDecoder.decode(url.getFile(), "UTF-8");
File jarFileOrClassesDir = new File(fileName);

but this causes problems if there is a + inside the path (the + is replaced with a space).

Upvotes: 0

Views: 53

Answers (1)

hradecek
hradecek

Reputation: 2513

but this causes problems if there is a + inside the path (the + is replaced with a space).

This is standar behavior of URLDecoder. See more information at JavaDoc [1], plus (+) is mentioned there as well.

Solution using Paths

Using Paths#get(URI) [2] should preserve all "special" symbols and you can pass directly URI which can be retrieved directly from URL using URL#toURI() [3].

So in summary:

final var filePath = Paths.get(url.toURI()); // We can extract any information from Path e.g. fileName.

shoud work as expected.


[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URLDecoder.html

[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Paths.html#get(java.net.URI)

[3] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/URL.html#toURI()

Upvotes: 1

Related Questions