views:

37

answers:

1

Hi there,

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

Thanks in advanced

+3  A: 

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
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
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
@testk: No problem. (Updated to fix the code)
Ash