Why does the user.dir property work in Java?

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

However, here are some of the things 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)

The test class is used here:

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 it now and expect it to work the same on all platforms?

+6
java filesystems chdir
source share
3 answers

Just because new File(".") Gives the desired answer does not mean that it does what you want.

For example, try:

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

Where does it end? In my windows window, although new File(".").getAbsolutePath() moves based on user.dir , foo.txt always created in the original working directory. It seems to me that the user.dir setting user.dir such that new File(".") Does not apply to the current working directory, it just asks for problems.

+10
source share

Quote:

The user.dir property is set when the VM starts as a working directory. You must not modify this property or set it on the command line. If you do this, you will see some inconsistent behavior, as there is a place in the implementation that assumes that user.dir is the working directory and that it does not change during the life of the VM.

Discussion here

+6
source share

File.getAbsoluteFile () just looks at the user.dir system property, which is a copy of the working directory of the process when the VM starts.

A better test would be to verify that the working directory of the process is actually changing. How you can do this, it depends on the platform, but on Linux you can do something like:

 $ ls -l /proc/18037/cwd lrwxrwxrwx 1 laurence laurence 0 2009-08-05 11:16 /proc/18037/cwd -> /home/laurence/ 

where "18037" is the pid of the process in question. If you do this, I believe that you will find that the working directory of the process does not actually change when updating user.dir.

+1
source share

All Articles