Java 更改文件工作目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19008592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Change File Working Directory
提问by Andy
I'm writing some unit tests. I'm running the tests by invoking the classes directly (rather than invoking another program). The problem is that some of these classes use data defined by relative paths, so they require that the program is started in a specific directory. How can I change this in Java?
我正在编写一些单元测试。我通过直接调用类(而不是调用另一个程序)来运行测试。问题是其中一些类使用由相对路径定义的数据,因此它们要求程序在特定目录中启动。如何在 Java 中更改此设置?
For instance, my unit test starts in C:/unittest
, and the data I need is in C:/OtherProject
. I don't want to modify the code of the other project if possible, is there something like this in java:
例如,我的单元测试开始于C:/unittest
,而我需要的数据在C:/OtherProject
. 如果可能的话,我不想修改另一个项目的代码,java中有没有这样的东西:
File.setWorkingDir("C:/OtherProject");
That way when something like
这样,当类似的事情
File file = new File("data/data.csv");
Will read C:/OtherProject/data/data.csv
instead of C:/unittest/data/data.csv
.
将读取C:/OtherProject/data/data.csv
而不是C:/unittest/data/data.csv
.
采纳答案by Bucket
Updating my answer, since VolkerSeibt pointed out that it was incorrect. Good catch.
更新我的答案,因为 VolkerSeibt 指出这是不正确的。接得好。
This is possible through System.setProperty
. You can change the current working directory by changing the "user.dir"
system property:
这可以通过System.setProperty
. 您可以通过更改"user.dir"
系统属性来更改当前工作目录:
System.setProperty("user.dir", "/foo/bar");
See http://www.javacodex.com/Files/Set-The-Current-Working-Directoryfor further explanation.
有关进一步说明,请参阅http://www.javacodex.com/Files/Set-The-Current-Working-Directory。