0

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

Keheck
  • 131
  • 1
  • 10
  • [thy this one](https://stackoverflow.com/questions/16239130/java-user-dir-property-what-exactly-does-it-mean) `System.getProperty("user.dir")` – Mr. Skip Nov 29 '18 at 19:34

1 Answers1

1

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.

gonzaloan
  • 371
  • 2
  • 13