Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Change File Working Directory [duplicate]

Tags:

java

io

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.

like image 300
Andy Avatar asked Sep 25 '13 15:09

Andy


People also ask

How to clone a file in Java?

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?

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.

Is there a way to get current working directory in Java?

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.

How do I move a file to another file in 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.

Is there a way to set the default directory location in Java?

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.


1 Answers

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.

like image 61
Bucket Avatar answered Oct 13 '22 17:10

Bucket