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

1
  • thy this one System.getProperty("user.dir") Commented Nov 29, 2018 at 19:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.