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

前端 未结 3 1913
渐次进展
渐次进展 2020-12-16 05:55

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 s

相关标签:
3条回答
  • 2020-12-16 05:56

    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.

    0 讨论(0)
  • 2020-12-16 06:07

    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

    0 讨论(0)
  • 2020-12-16 06:18

    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.

    0 讨论(0)
提交回复
热议问题