Changing the current working directory in Java?

242,453

Solution 1

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.

The File(String parent, String child) constructor can help if you build up your directory path separately from your file path, allowing easier swapping.

An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.

The relevant OpenJDK bug was closed in 2008 as "will not fix".

Solution 2

If you run your legacy program with ProcessBuilder, you will be able to specify its working directory.

Solution 3

There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.

import java.io.*;

public class FileUtils
{
    public static boolean setCurrentDirectory(String directory_name)
    {
        boolean result = false;  // Boolean indicating whether directory was set
        File    directory;       // Desired current working directory

        directory = new File(directory_name).getAbsoluteFile();
        if (directory.exists() || directory.mkdirs())
        {
            result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
        }

        return result;
    }

    public static PrintWriter openOutputFile(String file_name)
    {
        PrintWriter output = null;  // File to open for writing

        try
        {
            output = new PrintWriter(new File(file_name).getAbsoluteFile());
        }
        catch (Exception exception) {}

        return output;
    }

    public static void main(String[] args) throws Exception
    {
        FileUtils.openOutputFile("DefaultDirectoryFile.txt");
        FileUtils.setCurrentDirectory("NewCurrentDirectory");
        FileUtils.openOutputFile("CurrentDirectoryFile.txt");
    }
}

Solution 4

It is possible to change the PWD, using JNA/JNI to make calls to libc. The JRuby guys have a handy java library for making POSIX calls called jnr-posix. Here's the maven info

Solution 5

As mentioned you can't change the CWD of the JVM but if you were to launch another process using Runtime.exec() you can use the overloaded method that lets you specify the working directory. This is not really for running your Java program in another directory but for many cases when one needs to launch another program like a Perl script for example, you can specify the working directory of that script while leaving the working dir of the JVM unchanged.

See Runtime.exec javadocs

Specifically,

public Process exec(String[] cmdarray,String[] envp, File dir) throws IOException

where dir is the working directory to run the subprocess in

Share:
242,453

Related videos on Youtube

Nick
Author by

Nick

Updated on April 19, 2022

Comments

  • Nick
    Nick about 2 years

    How can I change the current working directory from within a Java program? Everything I've been able to find about the issue claims that you simply can't do it, but I can't believe that that's really the case.

    I have a piece of code that opens a file using a hard-coded relative file path from the directory it's normally started in, and I just want to be able to use that code from within a different Java program without having to start it from within a particular directory. It seems like you should just be able to call System.setProperty( "user.dir", "/path/to/dir" ), but as far as I can figure out, calling that line just silently fails and does nothing.

    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....

    • PhiLho
      PhiLho about 15 years
      Getting and using information is different from changing it. For example on Windows you can easily get environment variables but it is harder to change them (in system wide way).
    • Wolfgang Fahl
      Wolfgang Fahl almost 6 years
      bugs.java.com/bugdatabase/view_bug.do?bug_id=4045688 states in the evaluation section "Since that time, no further customers have come forward or were otherwise identified. ..." and as of 2018 we've got some 175.000 views of this question :-(
  • Nick
    Nick about 15 years
    Thanks. I had been able to find some other sources saying you couldn't do it, but I wasn't convinced until I saw that bug you linked to. Unfortunately it's not code I can easily modify, so I'll probably end up using something along the lines of the ".bat" solution you described.
  • Paul Biggar
    Paul Biggar over 12 years
    There doesn't seem to be a modern version of jna-posix. I forked and added one: github.com/pbiggar/jnr-posix. I can confirm that I can change the PWD with this.
  • Jake
    Jake over 12 years
    i don't think i've found a single difference between java and c# that makes me think, "those java guys sure know what they're doing"
  • maaartinus
    maaartinus about 12 years
    You seem to be mixing up environment variables and properties. The former gets inherited from the OS while the latter can be defined on the command line using -D. But I agree, on JVM start predefined properties like user.dir get copied from the OS and changing them later doesn't help.
  • Alnitak
    Alnitak about 12 years
    you can't do this in pure Java. You can do it with JNI.
  • rogerdpack
    rogerdpack over 11 years
    Hard to believe that java doesn't have some parameter "start in this directory..." at least...
  • Allen Rohner
    Allen Rohner over 11 years
    Yes. Sorry, I refactored that file and forgot this answer linked to the file. Fixed.
  • Borneq
    Borneq almost 11 years
    import javax.swing.filechooser.FileSystemView;
  • Tony K.
    Tony K. over 10 years
    In Java's defense (and I'm a UNIX guy that desires this feature)...it is a VM that is meant to be agnostic to OS particulars. The "present working directory" idiom is not available in some operating systems.
  • Ryan Leach
    Ryan Leach over 10 years
    To be fair to Java, they had to do it first, C# has had the benefit of being able to learn from their mistakes in a lot of areas.
  • David Mann
    David Mann over 10 years
    Because the piece of code contains a hard coded file path, and probably uses a hard-coded constructor that does not specify the parent directory to work from. Atleast, thats the situation I have :)
  • Morrie
    Morrie over 9 years
    You can do this, but if you don't also change the user.dir system property then File.getAbsolutePath() will resolve against user.dir, while the pathname in File resolves against the OS working directory.
  • Morrie
    Morrie over 9 years
    Changing user.dir affects File.getAbsolutePath() and File.getCanonicalPath(), but not the OS's idea of the working directory, which dictates how File pathnames are resolved when accessing files.
  • Sam Saint-Pettersen
    Sam Saint-Pettersen over 9 years
    In relation to the original question, using jnr-posix, how can I change the current working directory in Java. What class do I have to create a instance of to use the chdir method? I did not really understand the Clojure example given. Thanks in advance.
  • Volker Seibt
    Volker Seibt about 9 years
    That's wrong. See javacodex.com/Files/Set-The-Current-Working-Directory . Works at least on windows and linux.
  • palantus
    palantus about 9 years
    @VolkerSeibt: The answer below suggests that that only works with getAbsoluteFile or getAbsolutePath, but I just tried it and it seems you are correct.
  • palantus
    palantus about 9 years
    @VolkerSeibt: On further investigation, it seems that user.dir only works for some classes, including the one I tested with at first. new FileOutputStream("foo.txt").close(); creates the file in the original working directory even if user.dir is changed by the program.
  • John
    John almost 9 years
    This seems to be a better answer than the accepted answer (which starts with "There is no reliable way to do this in pure Java. "). Is there a way to petition for this answer to be considered as the accepted answer?
  • Aaron Digulla
    Aaron Digulla about 8 years
    This answer is not related to the question.
  • user207421
    user207421 almost 7 years
    But it doesn't change the current working directory. Only the value of user.dir. The fact that the absolute path becomes critical proves it.
  • CatsAndCode
    CatsAndCode over 6 years
    's route is the route I took. I was able to run an executable from a different working directory with the following: File WorkingDir = new File("C:\\path\\to\\working\\dir\\"); ProcessBuilder pBuilder = new ProcessBuilder("C:\\path\\to\\working\\dir\\executable.exe")‌​; pBuilder.directory(WorkingDir); Process p = pBuilder.start();
  • Gangnus
    Gangnus about 5 years
    "It creates a file Object" - yes. But it does not create a file in the filesystem. You forgot to use file.createNewFile() after that.
  • Martin
    Martin over 4 years
    Please note that this behavior changed in Java 11, see bugs.openjdk.java.net/browse/JDK-8202127. They do not recommend using System.setProperty("user.dir", "/some/directory")