Changing the current working directory in Java?

前端 未结 14 1659
太阳男子
太阳男子 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: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");
        }
    }
    

提交回复
热议问题