Why is the user.dir system property working in Java?

Geo picture Geo · Aug 5, 2009 · Viewed 15.9k times · Source

Almost every article I read told me that you can't have chdir in Java. The accepted answer to this question says you can't do it in Java.

However, here's some of the stuff I tried:

geo@codebox:~$ java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode, sharing)

Here's a test class I'm using:

import java.io.*;

public class Ch {
    public static void main(String[] args) {
        System.out.println(new File(".").getAbsolutePath());
        System.setProperty("user.dir","/media");
        System.out.println(new File(".").getAbsolutePath());
    }
}
geo@codebox:~$ pwd
/home/geo
geo@codebox:~$ java Ch
/home/geo/.
/media/.

Please explain why this worked. Can I use this from now on and expect it to work the same way on all platforms?

Answer

Jon Skeet picture Jon Skeet · Aug 5, 2009

Just because new File(".") gives the desired answer doesn't mean it's doing what you want it to.

For example, try:

new FileOutputStream("foo.txt").close();

Where does that end up? On my Windows box, even though new File(".").getAbsolutePath() moves around based on user.dir, foo.txt is always created in the original working directory. It strikes me that setting user.dir such that new File(".") doesn't refer to the current working directory is just asking for trouble.