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
.
Another common way to copy a file with Java is by using the commons-io library. The latest version can be downloaded from Maven Central. Then, to copy a file we just need to use the copyFile() method defined in the FileUtils class. The method takes a source and a target file.
Is it possible to change directory by using File object in Java? The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
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.... Show activity on this post. There is no reliable way to do this in pure Java.
The static move () method of the Files class in the java.nio.file package is platform-independent and have options to replace the destination file if exists: Files.move (Path source, Path target, CopyOptions… options) This method returns the path to the target file, and throws exception if the operation failed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With