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

十年热恋 提交于 2019-11-27 16:45:13

问题


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?


回答1:


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.




回答2:


Quote:

The user.dir property is set at VM startup to be the working directory. You should not change this property or set it on the command-line. If you do, then you will see some inconsistent behaviour as there places in the implementation that assumes that the user.dir is the working directory and that it doesn't change during the lifetime of the VM.

The discussion is here




回答3:


File.getAbsoluteFile() is just looking at the user.dir system property, which is a copy of the process's working directory at VM startup.

A better test might be to check that the process's working directory is actually changing. How you can do this varies by platform, but on Linux you can to 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 you'll find that the process's working directory doesn't actually change when you update user.dir.



来源:https://stackoverflow.com/questions/1234795/why-is-the-user-dir-system-property-working-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!