Changing the current working directory in Java?

前端 未结 14 1502
太阳男子
太阳男子 2020-11-22 05:32

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\

相关标签:
14条回答
  • 2020-11-22 05:45

    I have tried to invoke

    String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());

    It seems to work. But

    File myFile = new File("localpath.ext"); InputStream openit = new FileInputStream(myFile);

    throws a FileNotFoundException though

    myFile.getAbsolutePath()

    shows the correct path. I have read this. I think the problem is:

    • Java knows the current directory with the new setting.
    • But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.

    The solution may be:

    File myFile = new File(System.getPropety("user.dir"), "localpath.ext");

    It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.

    ~~~~JcHartmut

    0 讨论(0)
  • 2020-11-22 05:45

    The other possible answer to this question may depend on the reason you are opening the file. Is this a property file or a file that has some configuration related to your application?

    If this is the case you may consider trying to load the file through the classpath loader, this way you can load any file Java has access to.

    0 讨论(0)
  • 2020-11-22 05:46

    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");
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:46

    The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt"), just build the path to the file yourself.

    Let the user pass in the base directory, read it from a config file, fall back to user.dir if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.

    0 讨论(0)
  • 2020-11-22 05:51

    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 Sun bug was closed in 2008 as "will not fix".

    0 讨论(0)
  • 2020-11-22 05:52

    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

    0 讨论(0)
提交回复
热议问题