2

I'm trying to get the path to a file that it is located out of the java jar and I don't want to use an absolute path. An exampel: lets say that the jar is located in ~/lib/myjar.jar and the file is located in the same folder. What I've trying is something like this, but it fails:

File myfile = new File(this.getClass().getResource("../../../").toURI());

Note: my package is com.contro.gui, that's why I have "../../../", in order to acces to the "root"

I'm not sure how I can access to the file. Any suggestion?? And what about if the file that I want to access is in other folder like ~/res/ ???

BЈовић
  • 62,405
  • 41
  • 173
  • 273
testk
  • 147
  • 2
  • 7
  • There are three variants of solution, depending on the situation: https://stackoverflow.com/a/56327069/715269 – Gangnus May 27 '19 at 13:38

2 Answers2

5

If the file is in the same directory as the jar, I think this will work (feels fairly hacky, but...):

URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
File myfile = new File(url.toURI());
File dir = myfile.getParentFile(); // strip off .jar file

(Haven't tested this, but it seems feasible. Will only work with file-based jars of course).

If the file is in some random location, I think you will need to either pass in parameters or check "known" locations like user.home. (Or, you could always put the file in the jar a use getResource().)

Ash
  • 9,296
  • 2
  • 24
  • 32
  • Perfect!! It worked as expected! Thank you so much! I was breaking my head trying millions of options. Only one modification...instead of "myfile.getParent()", it is "myfile.getParentFile()" – testk Oct 14 '10 at 03:48
  • One side note: I looks like, what I posted, it works if you have the right classpath. But your solution it's better. Thanks! – testk Oct 14 '10 at 03:49
  • I get the exception : " java.lang.IllegalArgumentException: URI is not hierarchical" – AnirbanDebnath Dec 14 '19 at 14:19
0

No just do

     File FileName = new File(".");
     String Directory = FileName.getCanonicalPath();

that will get you the parent directory of your class in a file or jar just remember to set the directory if it's in a jar like this "NameOfJar\NameOfFolder\etc"

CoderCub
  • 1
  • 1