我读过的几乎每篇文章都告诉我,你不能用Java创建chdir。 这个问题的公认答案说你不能用Java做到这一点。
但是,这里有一些我尝试过的东西:
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)
这是我正在使用的测试类:
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/.
请解释为什么这有效。 从现在开始我可以使用它并期望它在所有平台上以相同的方式工作吗?
仅仅因为new File(".")给出了所需的答案并不意味着它正在做你想要的。
例如,尝试:
new FileOutputStream("foo.txt").close();
那最终会在哪里?在我的Windows框中,即使new File(".").getAbsolutePath()基于user.dir移动,也始终在原始工作目录中创建foo.txt。设置user.dir使得new File(".")不引用当前工作目录只会让人感到麻烦。
我没有测试:)。 当我看到更改user.dir属性时,我停止了File类。
那就是......所以......所以......错了。:-)
引用:
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.
讨论就在这里
File.getAbsoluteFile()只是查看user.dir系统属性,它是VM启动时进程工作目录的副本。
更好的测试可能是检查进程的工作目录是否实际发生了变化。如何做到这一点因平台而异,但在Linux上你可以这样:
$ ls -l /proc/18037/cwd
lrwxrwxrwx 1 laurence laurence 0 2009-08-05 11:16 /proc/18037/cwd -> /home/laurence/
其中"18037"是该过程的pid。如果你这样做,我相信你会发现当你更新user.dir时,进程的工作目录实际上没有改变。