Search code examples
javaresourcesjarfilepathpathname

How to get a path to a resource/file out of a Java JAR file


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/ ???


Solution

  • 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().)