This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do I get the path to a running JAR file?

My code runs in a JAR file, such as foo. JAR, and I need to know in my code what folder foo. JAR is running in.

So, if foo.jar is in C:\ foo \, I want to get that path no matter what my current working directory is.

Answer 1:

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
Copy the code

Replacing “MyClass” with your own class, toURI() is essential to avoid problems with special characters, including Spaces and plus signs.

Answer 2:

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
Copy the code

This solution solves the problem of whitespace and special characters.

One more thing to note: When I call this function from a Jar, the name of the Jar is appended to the string I returned last, so I must execute:

path.substring(0, path.lastIndexOf("/") + 1);
Copy the code

Answer 3: Paths class

public final class Paths {
    private Paths(a) {}public static Path get(String first, String... more) {
        return Path.of(first, more);

    public static Path get(URI uri) {
        returnPath.of(uri); }}Copy the code

Let’s take a look at what the of method of the Path class actually is

static Path of(URI uri) {
        String scheme = uri.getScheme();
        if (scheme == null) {
            throw new IllegalArgumentException("Missing scheme");
        } else if (scheme.equalsIgnoreCase("file")) {
            return FileSystems.getDefault().provider().getPath(uri);
        } else {
            Iterator var2 = FileSystemProvider.installedProviders().iterator();

            FileSystemProvider provider;
            do {
                if(! var2.hasNext()) {throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed");

                provider = (FileSystemProvider);
            } while(! provider.getScheme().equalsIgnoreCase(scheme));returnprovider.getPath(uri); }}Copy the code

Final implementation:

Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Copy the code

The article translated from Stack Overflow:…