Thursday, February 14, 2008

[JAVA] How to Retrieve Application Path

This brief article will explain in a few lines how to retrieve the application path in a JAVA enviroment, both the official way and the butchers' way (just as we like!).

(1) The first way calls the System.getProperty static method passing the user.dir value:

String dir = System.getProperty("user.dir");

This way is simple but I found that sometimes (I'm not sure if Sun has fixed it) the returned directory could be slightly different from the one in which the application resides: this is because some times it gives out the directory in which the application has been started and not the one where your classes are.

This happened to me using Eclipse Plugins: usign several plugins, I needed a common directory to retrieve some XML resources, but the working directory returned was the one in which eclipse was running and of course not the same of the plugins one.

I fixed it using a ResourceBundle class. Actually that wasn't a bug, because most of libraries needed to run my plugins were inside Eclipse directory.

(2)And now the butchers' method! This method creates a fictitious file and retrieves its absolute path: I found that this method can overcome the problems using user.dir system property:

java.io.File currentDir = new java.io.File("");
String dir = currentDir.getAbsolutePath();

Generally to retrieve your resources that are in a class directory (and maybe not in the working directory) you won't need the entire path, because we can use this method:
InputStream in = MyClass.class.getResourceAsStream("MyImage.gif");

So my advice is using paths of external directories and storing them into configuration files (such as .properties files) or calling resources without using absolute paths; moreover don't try to modify user.dir system property because it is set when your application starts and if you change it you don't know how will be the behaviour of all other classes.

Stay tuned!

3 comments:

Johnny Idol said...

way to go Scuffia

Sam said...

I learned something today, thanks!

x@ES said...

System.getProperty("user.dir") - it is current directory. It is not bug, when user.dir not same as application classes path.