在 Java 中更改当前工作目录? [英] Changing the current working directory in Java?

查看:46
本文介绍了在 Java 中更改当前工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Java 程序中更改当前工作目录?我所能找到的关于这个问题的所有信息都声称你根本无法做到,但我不敢相信事实确实如此.

How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.

我有一段代码,它使用硬编码的相对文件路径从它通常启动的目录中打开一个文件,我只想能够在不同的 Java 程序中使用该代码而无需启动它来自特定目录.看起来你应该能够调用 System.setProperty( "user.dir", "/path/to/dir" ),但据我所知,只调用那条线默默地失败,什么也不做.

I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.

如果 Java 不允许您这样做,我会理解,如果不是因为它允许您获取当前工作目录,甚至允许您打开文件使用相对文件路径....

I would understand if Java didn't allow you to do this, if it weren't for the fact that it allows you to get the current working directory, and even allows you to open files using relative file paths....

推荐答案

在纯 Java 中没有可靠的方法来做到这一点.通过 System.setProperty()java -Duser.dir=... 设置 user.dir 属性似乎会影响后续创建文件,但不是例如FileOutputStreams.

There is no reliable way to do this in pure Java. Setting the user.dir property via System.setProperty() or java -Duser.dir=... does seem to affect subsequent creations of Files, but not e.g. FileOutputStreams.

File(String parent, String child) 构造函数可以提供帮助,如果您将目录路径与文件路径分开构建,从而更容易交换.

The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.

另一种方法是设置脚本以从不同的目录运行 Java,或使用 JNI 本机代码如下建议.

An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.

相关的 Sun 错误已于 2008 年关闭,因为不会修复".

The relevant Sun bug was closed in 2008 as "will not fix".

这篇关于在 Java 中更改当前工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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