Reputation: 133
I want to use image files for my java program, and for that I need File
objects. But I have the problem that when I build my project, the project name has a .jar
at the end of the name, making a File object like new File("..\\Project\\src\\ImageDirectory\\Image.png")
useless, since the directory doesn't exist.
I've found out I could tecnically iterate through all the directorys on the computer but I don't want to do that because that could take some time with high amounts of directories and harddrives.
So, is there a reliable and easy way to get the directory the jar file is currently in?
My IDE is InellijIDEA
Upvotes: 0
Views: 90
Reputation: 371
You can use Path to do this:
Path path = Paths.get(YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI());
Path have several methods to get more information.
For example, i have this JAR in Desktop and i am printing this:
System.out.println(path);
System.out.println(path.getRoot());
System.out.println(path.getParent());
The results are:
java -jar C:\Users\gmunozme\Desktop\Test.jar
C:\Users\gmunozme\Desktop\Test.jar
C:\
C:\Users\gmunozme\Desktop
Check that out, Hope you can use it.
Upvotes: 1