12

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.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Andy
  • 3,228
  • 8
  • 40
  • 65

1 Answers1

15

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.

Bucket
  • 7,415
  • 9
  • 35
  • 45
  • I've done quite a lot of looking round, this does seem the case. I've solved it by just having a static class 'FileUtil' that I store the working directory in (and have accessors), and then a function 'loadFile' which essentially just prepends the working directory to the passed file path. – Andy Jan 20 '14 at 15:28
  • 1
    Thats wrong. See http://www.javacodex.com/Files/Set-The-Current-Working-Directory . Works at least on windows and linux. – Volker Seibt Jun 09 '15 at 13:43
  • @VolkerSeibt: Good catch. I have updated my answer. – Bucket Jun 23 '15 at 20:04