Showing posts with label butchering. Show all posts
Showing posts with label butchering. Show all posts

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!

Friday, September 7, 2007

[DISCLAIMER]

Hi,

I am Johnny Idol (AKA Giovacchia) and this is a blog about software development and computing related incredible messes, solved in mysterious ways or not solved at all.

[DISCLAIMER]
In wartime there are no compromises, you gotta be as fast as you can and watch your ass at the same time. Imagine a doctor in the middle of a battle trying to save injured soldiers: is he going to care about the simmetry of the stitches or spend a lot of time on every guy? Maybe he tried once, and one of the guys is now perfectly healthy, but a significant percentage of the others is resting in peace. He learned then that in wartime it can't take too long.
Best practices are what we like to read and speak about, but butchery is what we secretely do.

Gotta go track some bugs,

talk you soon.