How to get the current directory in Java?

A useful tip to share with you.

I need to read the file from the current directory (same directory with the main jar file). In my code, I just use "new File("test")", and it works quite well.

But in my colleague’s machine, it throws the FileNotFound exception. Oh, we I saw the exception in his screen, I know that it’s a careless fault.
The problem is I accessed files in a given
location without an absolute path prefix.

In my case:

cd /home/elan/test/
java -jar test.jar

So, the current working directory is "/home/elan/test/", and we can access the file by a relative path.

My colleague’s case:

cd /usr/java/bin
java -jar /home/elan/test/test.jar

The working directory is "/usr/java/bin", and no "test" existed in this folder.

Ok, then how to get the current directory?

As we know, System.getProperty("user.dir") will get the working directory and System.getProperty("user.home") will get the home directory ("/home/elan/" for linux and "$:/document and settings/elan/" for windows case), but I cannot get any clue to get the current directory which contains my jar file and the "test" file.

I have thought that I can get this kind of code in "java.io" or "runtime" classes, but
I cannot find any clue. So, how about get the location of the jar file since it’s the file that in this directory. After a while, I got the answer:

getClass().getProtectionDomain().getCodeSource().getLocation()

It will return the class code base’s location, and in my case, the jar file’s location. So I just need to get the parent path of this location. The problem solved.

BTW:

1) You’d better pack the file into the jar and use the classloader to read it;

2) Or you can use the home directory ( System.getProperty("user.home") )

3) In my case, for some special reason, I must do this. :P

Popularity: 10% [?]

Related entries:

Leave a comment

(required)

(required)


Information for comment users
Line and paragraph breaks are implemented automatically. Your e-mail address is never displayed. Please consider what you're posting.

Use the buttons below to customise your comment.


RSS feed for comments on this post |