为什么 user.dir 系统属性在 Java 中起作用?
我读过的几乎每一篇文章都告诉我在 Java 中不能有 chdir。 这个问题的公认答案说你不能这样做爪哇。
但是,这是我尝试过的一些内容:
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/.
请解释为什么它有效。 我可以从现在开始使用它并期望它在所有平台上都以相同的方式工作吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅仅因为
new File(".")
给出了所需的答案并不意味着它正在执行您想要的操作。例如,尝试:
最终会在哪里? 在我的 Windows 机器上,即使
new File(".").getAbsolutePath()
基于user.dir
、foo.txt
移动始终在原始工作目录中创建。 让我印象深刻的是,设置user.dir
使得new File(".")
不引用当前工作目录只是在询问为了麻烦。Just because
new File(".")
gives the desired answer doesn't mean it's doing what you want it to.For example, try:
Where does that end up? On my Windows box, even though
new File(".").getAbsolutePath()
moves around based onuser.dir
,foo.txt
is always created in the original working directory. It strikes me that settinguser.dir
such thatnew File(".")
doesn't refer to the current working directory is just asking for trouble.引用:
讨论位于此处
Quote:
The discussion is here
File.getAbsoluteFile() 只是查看 user.dir 系统属性,它是虚拟机启动时进程工作目录的副本。
更好的测试可能是检查进程的工作目录是否确实发生了变化。 如何执行此操作因平台而异,但在 Linux 上,您可以执行以下操作:
其中“18037”是相关进程的 pid。 如果你这样做,我相信你会发现当你更新 user.dir 时进程的工作目录实际上并没有改变。
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:
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.