In Java, we can use the following code snippets to get the path of a running JAR file.
// static
String jarPath = ClassName.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
// non-static
String jarPath = getClass()
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
Sample output.
/home/favtuts/projects/core-java/java-io/target/java-io.jar
1. Get the path of running JAR
1.1 Create an executable JAR file.
pom.xml
<!-- Make this jar executable -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.favtuts.io.howto.resources.TestApp</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
1.2 Run the below code to get the name or path of the running JAR file.
TestApp.java
package com.favtuts.io.howto.resources;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
TestApp obj = new TestApp();
try {
// Get path of the JAR file
String jarPath = TestApp.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
System.out.println("JAR Path : " + jarPath);
// Get name of the JAR file
String jarName = jarPath.substring(jarPath.lastIndexOf("/") + 1);
System.out.printf("JAR Name: " + jarName);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
Output
$ mvn clean package
$ java -jar target/java-io.jar
JAR Path : /home/mkyong/projects/core-java/java-io/target/java-io.jar
JAR Name: java-io.jar
2. toURI()?
If the file name or file path contains special characters, for example, %, the .getLocation.getPath() will encode the special characters.
try {
// return raw, no encode
String jarPath = TestApp.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
System.out.println("JAR Path : " + jarPath);
// url encoded
String jarPath2 = TestApp.class
.getProtectionDomain()
.getCodeSource()
.getLocation() //.toURI
.getPath();
System.out.println("JAR Path 2 : " + jarPath2);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Output
$ java -jar java-io%test.jar
JAR Path : /home/favtuts/projects/core-java/java-io/target/java-io%test.jar
JAR Path 2 : /home/favtuts/projects/core-java/java-io/target/java-io%25test.jar
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-io