20050608 星期三 2005年06月08日

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

( 2005年06月08日, 06:29:07 下午 GMT+08:00 ) Permalink 评论 [9]

Apple's shift to Intel-based chips

Just abstract some comments here. To imagine the Mac OS based on Solaris, the good UI experience plus the the world's highest volume and most secure UNIX. :-)

" So I'd like to personally invite you to adopt Solaris 10 as the underpinning of the next generation Mac. We both respect Unix, both respect innovation*, and both clearly see volume opportunities in extending choice to developers. We'd love to work together. " - Jonathan

"Usually there are two players rather than three: the favorite and the underdog. The "third" person does not matter as much. With Apple moving to x86 it can quickly become the underdog of the platform and put Linux in third (outsider) place." - Slashdot

( 2005年06月08日, 11:30:38 上午 GMT+08:00 ) Permalink 评论 [1]