Java Change File Working Directory [duplicate]

2020-07-05 06:17发布

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?

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

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.

标签: java io
1条回答
别忘想泡老子
2楼-- · 2020-07-05 07:04

Updating my answer, since VolkerSeibt pointed out that it was incorrect. Good catch.

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

See http://www.javacodex.com/Files/Set-The-Current-Working-Directory for further explanation.

查看更多
登录 后发表回答