- How to get a path to a resource in a Java JAR file
- Pass Resources Folder path to the command when running a jar
- How to get file path to a resource inside a jar
- Jar File can’t find image file path
- Using toURI() and toString()
- Using toExternalForm()
- Using File and toURI()
- Summary
- Java — Getting The Path Of The Jar File
- How to Get the Physical Location of a JAR File
- How to get the current directory path of a JAR in Java
- System.Property
- File and NIO Files API
- When the path value is not the expected JAR location
- References
How to get a path to a resource in a Java JAR file
If it isn’t there, then load the default version of this file, packed into your jar, by reading it with , and write it to that location, then inform the user they can edit it there. Having a file that you write to from your own process next to your jar is a bad security practice and in general an obsolete application model, going on 20 years now.
Pass Resources Folder path to the command when running a jar
I have built a Jar File without including my resource folder. Because property file need to be edited when running the jar. But I am not aware how to pass the resources folder path along with the jar command. Current command that I use to run the jar is as follows
I also tried below command
java -jar myProject.jar -Dconfig=/a/full/path
UPDATE As I want to edit my property file before running the jar file I don’t want to embed resources folder within the jar file. I need the resources folder path to be passed to the command which used to run the jar file
Using the resources system ( MyClass.class.getResource / getResourceAsStream is the right way; commonly written as MyClass.class.getClassLoader().getResource or getClass().getResource or getClass().getClassLoader().getResource() which are all subtly wrong) is not correct for ‘mutable’ files.
If there is a properties file, then look for it in the user’s home dir ( Paths.get(System.getProperty(«user.home»), «myapp.properties») . If it isn’t there, then load the default version of this file, packed into your jar, by reading it with .getResource , and write it to that location, then inform the user they can edit it there.
Having a file that you write to from your own process next to your jar is a bad security practice and in general an obsolete application model, going on 20 years now. Directories containing executable code should not be writable except by the user themselves and admin users. An app has absolutely no business writing anything anywhere near executables. If your system even lets you, then your OS / your user settings are misconfigured. Or at the very least, assuming (i.e. forcing ) a user of a computer to run in a mode that means the processes they start can write to the place the executables live — is just bad software.
conclusion: You think you want to write to a properties file that lives next to your jar, but you don’t. Instead, write in user.home — that’s what it is for.
How to get the path and name of the current running jar?, File dir = new File(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()); String jar = System.
How to get file path to a resource inside a jar
I am trying to load a file which is in src/main/resources. It works fine in my local but when I deploy a jar , seeing an issue . I know how to get the Inputstream but in my case I need to load file.
File location:
src main resources cert truststore.ks
String filename = cert/truststore.ks
spark.sparkContext().addFile(getAbsolutePath(filename));
public String getAbsolutePath(String fileName) throws IOException, URISyntaxException
Exception in thread "main" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.spark.deploy.worker.DriverWrapper$.main(DriverWrapper.scala:65) at org.apache.spark.deploy.worker.DriverWrapper.main(DriverWrapper.scala) Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: jar:file:/work/run/driver-20200525203940-0037/service-1.0.0-SNAPSHOT.jar!/cert/truststore.ks at org.apache.hadoop.fs.Path.initialize(Path.java:205) at org.apache.hadoop.fs.Path.(Path.java:171) at org.apache.spark.SparkContext.addFile(SparkContext.scala:1519) at org.apache.spark.SparkContext.addFile(SparkContext.scala:1499) Caused by: java.net.URISyntaxException: Relative path in absolute URI: jar:file:/work/run/driver-20200525203940-0037/service-1.0.0-SNAPSHOT.jar!/cert/truststore.ks at java.net.URI.checkPath(URI.java:1823) at java.net.URI.(URI.java:745) at org.apache.hadoop.fs.Path.initialize(Path.java:202)
For Example follow this gist
How to get spring boot application jar parent folder path dynamically?, ApplicationHome home = new ApplicationHome(MyMainSpringBootApplication.class); home.getDir(); // returns the folder where the jar is. This is
Jar File can’t find image file path
I’m creating a simple program that I now want to export as a executable jar file. Everything works fine except the jar file can’t find the image.
For creating the runnable JAR file I used the second option in Eclipse 2021-12 (Package required libraries into generated JAR). This seems to work well, because I only have the jar and no other folders I need to run the program.
My jar file structure looks like this:
jar_file/
├─ images/
│ ├─ frog.png
I’ve tried multiple ways of getting the image file.
This is how I define Icon:
private static Image icon;
Using toURI() and toString()
This does not work in Eclipse.
Path Output: file:/C:/Projekte/serviceticketapp/target/classes/images/frog.png
This does not work in the Jar File.
Path Output: rsrc:images/frog.png
Using toExternalForm()
This does not work in Eclipse.
Path Output: file:/C:/Projekte/serviceticketapp/target/classes/images/frog.png
This does not work in the Jar File.
Path Output: rsrc:images/frog.png
Using File and toURI()
File imageFile = new File(getClass().getResource(«/images/frog.png»).toURI()); icon = Toolkit.getDefaultToolkit().getImage(imageFile.getAbsolutePath());
Path Output: C:\Projekte\serviceticketapp\target\classes\images\frog.png
java.lang.IllegalArgumentException: URI is not hierarchical
Summary
Above you can see all the ways I tried to get the image file. Only one works in Eclipse and none of them work in the jar file.
What am I doing wrong or how do I have to arrange the files in order for it to work in the jar file and in Eclipse.
Please ask if you need more information. Thanks in advance.
I would use imagio ( import javax.imageio.ImageIO )
tIcon = new TrayIcon(ImageIO.read(getClass().getResource("/images/frog.png"), "Service Ticket App");
How to get filepath of the located file when ran from JAR in JAVA?, File file = getFileFromResources(«Utility/ConfigurationXML.xml»); strFilePath = file.getAbsolutePath();. which gives me the absolute path of the
Java — Getting The Path Of The Jar File
Whenever you are working with files in Java, sometimes you need to get the full path to the directory the .jar file is located in. Most of the time you can just use
. String path = «./File_Name.txt»; // Note the «.» before the «/»
.
when dealing with reading/writing/creating files and directories — HOWEVER for those times when that is not enough, you’ll need to extract a «clean» path to the .jar file.
Below is a simplified example that does exactly this. I cut out all of the unnecessary, over complicated, and/or outdated items you may find in other posts about this subject.
I will explain how it works as we go along.
. public class Main < public static void main (String[] args) throws Exception < String i; // ignore - not important String pathName; // path to create new file String fileName; // name of new file File file; // File object to create i = "\n**********\n"; // ignore - not important fileName = "/Test_File.txt"; // set the file name pathName = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); // get the path of the .jar pathName = URLDecoder.decode(pathName,"utf-8"); // convert the path format from HTML to UTF pathName = pathName.substring(1,pathName.lastIndexOf("/") ); //create a new string by removing the garbage System.out.println(i + pathName + fileName + i ); // this is for debugging - see the results file = new File(pathName + fileName); // create file file.createNewFile(); // make new file >>
.
.
. pathName = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
.
This returns the *raw* path of the .jar file in a HTML format with some extra junk that is not needed. Using «.toURI()», «.toURL()» and «.toString() is not necessary AND will create more junk in the path name!
.[quote]
C:\Users\RICK\Desktop>java -jar test1111.jar
**********
/C:/Users/RICK/Desktop/Test1111.jar
**********
[/quote].
Note: If you have any directories with special characters in them, you will end up with the HTML equivalent . «%20″ instead of » » for example.
The next line parses the HTML format into UTF, which Java can understand as a path name
. pathName = URLDecoder.decode(pathName,»utf-8″);
.
This cleans up the HTML format, but leaves some junk behind
.[quote]
C:\Users\RICK\Desktop>java -jar test1111.jar
**********
/C:/Users/RICK/Desktop/Test1111.jar
**********[/quote].
Now we need to remove the junk, and create a usable path for Java to use
. pathName = pathName.substring(1,pathName.lastIndexOf(«/») );
.
This removed the first «/» from the string, and also cuts off the name of the .jar file !
This creates a usable path name, to be used, in this example, to make a file
. file = new File(pathName + fileName); file.createNewFile();
.
.[quote]
C:\Users\RICK\Desktop>java -jar test1111.jar
**********
C:/Users/RICK/Desktop/Test_File.txt
**********[/quote].
Thank you for reading. Please leave feedback below !
How to Get the Physical Location of a JAR File
In this tutorial, I will demonstrate how to find the jar file associated with a given class. In the past, I’ve used this information to debug class loaders, identify the version number of a given library, run apps found relative to a jar file, store configuration information, etc.
Here’s a simple command line app used to return the physical location of the jar file. Note the 2 getJarFile() methods. One is used to find the physical location given a «Class», while the other will return a location using an instance of a class.
public class Test < public static void main(String[] args) throws Exception < System.out.println(getJarFile(Test.class)); >public static java.io.File getJarFile(Object obj) throws Exception < return getJarFile(obj.getClass()); >public static java.io.File getJarFile(Class _class) throws Exception < String path = _class.getPackage().getName().replace(".","/"); String url = _class.getClassLoader().getResource(path).toString(); url = url.replace(" ","%20"); java.net.URI uri = new java.net.URI(url); if (uri.getPath()==null)< path = uri.toString(); if (path.startsWith("jar:file:"))< //Update Path and Define Zipped File path = path.substring(path.indexOf("file:/")); path = path.substring(0,path.toLowerCase().indexOf(".jar")+4); if (path.startsWith("file://"))< //UNC Path path = "C:/" + path.substring(path.indexOf("file:/")+7); path = "/" + new java.net.URI(path).getPath(); >else < path = new java.net.URI(path).getPath(); >return new java.io.File(path); > > else < return new java.io.File(uri); >return null; > >
Note that these JAR utilities/functions and more are available in the javaxt.io.Jar class.
How to get the current directory path of a JAR in Java
It’s a common task in applications to require to interact with files located in a relative path from where the application is executed. In the case of Java there isn’t a specific API to get that value, however there are a lot of ways to get the value easily. Let’s see them.
System.Property
When we execute a Java application, it has a lot properties populated by default by the JVM, one of them is the “ user.dir ” property, and its value contains the “user working directory“, which in most of the cases will have the directory of the jar executable.
String userDirectory = System.getProperty("user.dir");
File and NIO Files API
Another approach is using the Files API to get the current directory, using the relative path «.» or an empty relative path, it should return the current location of the executable.
//Using the Old File api String userDirectory2 = new File("").getAbsolutePath(); //Using Files NIO api String userDirectory3 = Paths.get("") .toAbsolutePath() .toString();
The relative “empty” or «.» path will use the user current working directory internally. Therefore, it will return the same value as the “user.dir” approach.
When the path value is not the expected JAR location
There are some situations where the values returned by the previous approaches doesn’t return the expected value where the JAR is located.
- On Linux, running the jar file by opening it from the File Explorer (eg, double click on the jar file). It will return the home directory of the user, regardless of the location where the jar is located.
- On Windows, in some old versions, running jar from command line with “Admin User permissions” might return “ C://windows/system32 “
This is because the user working directory indicated by the system might not be the jar location. For example, in Linux File explorer even though we have navigated through the folders and the path is different than the home directory, when the JAR is executed the “user.dir” property will contain the home directory. This will not happened when navigating through the command line, because the cd command will override the working directory of the user.
For that purpose we can use following snippet code:
File file = new File(MyClass.class.getProtectionDomain().getCodeSource() .getLocation().toURI().getPath()); String basePath = file.getParent();
The first line will return the location of the jar file. The second line will get the container directory of that file.
public class MyApp < static < //This static block runs at the very begin of the APP, even before the main method. try< File file = new File(MyApp.class.getProtectionDomain().getCodeSource() .getLocation().toURI().getPath()); String basePath = file.getParent(); //Overrides the existing value of "user.dir" System.getProperties().put("user.dir", basePath); >catch(Exception ex) < //log the error >> public static void main(String args []) < //Your app logic // Use any of the other approaches with the expected value String userDirectory = System.getProperty("user.dir"); String userDirectory2 = new File("").getAbsolutePath(); >>
With that static block of code at the very beginning of the application, we can get the real location of the JAR file and override the value of the system property “ user.dir “. So, we can use any of the other approaches in the application logic, and see the value is the expected regardless of the way the application was executed (command line, double click) or the environment (Windows, Linux, Mac).