为什么在Java中使用user.dir系统属性? [英] Why is the user.dir system property working in Java?

查看:448
本文介绍了为什么在Java中使用user.dir系统属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几乎每篇文章都告诉我,你不能在Java中使用 chdir 这个问题接受的答案说,你不能这样做Java。



然而,下面是我尝试的一些东西:

 
geo @codebox:〜$ java -version
java版本1.6.0_14
Java™SE运行时环境(build 1.6.0_14-b08)
Java HotSpot™客户端虚拟机构建14.0-b16,混合模式,共享)

以下是我正在使用的测试类:

  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());





$ b $ 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 ,使得新的文件(。) 参考当前的工作目录只是要求麻烦。


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?

解决方案

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.

这篇关于为什么在Java中使用user.dir系统属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆