问题描述
我正在写一些单元测试。我通过直接调用类来运行测试(而不是调用另一个程序)。问题是这些类中的一些使用由相对路径定义的数据,因此它们要求程序在特定目录中启动。如何在Java中更改此内容?
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?
例如,我的单元测试从 C:/ unittest
开始,并且我需要的数据是 C:/ OtherProject
。如果可能,我不想修改其他项目的代码,在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:
File.setWorkingDir("C:/OtherProject");
这种方式类似于
File file = new File("data/data.csv");
将读取 C:/OtherProject/data/data.csv
而不是 C:/unittest/data/data.csv
。
推荐答案
更新我的答案,因为VolkerSeibt指出它是不正确的。好的捕获。
Updating my answer, since VolkerSeibt pointed out that it was incorrect. Good catch.
这可以通过 System.setProperty
来实现。您可以通过更改user.dir
系统属性来更改当前工作目录:
This is possible through System.setProperty
. You can change the current working directory by changing the "user.dir"
system property:
System.setProperty("user.dir", "/foo/bar");
参见有待进一步说明。
这篇关于Java更改文件工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!