Changing the current working directory in Java?

前端 未结 14 1488
太阳男子
太阳男子 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:36

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

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

    You can change the process's actual working directory using JNI or JNA.

    With JNI, you can use native functions to set the directory. The POSIX method is chdir(). On Windows, you can use SetCurrentDirectory().

    With JNA, you can wrap the native functions in Java binders.

    For Windows:

    private static interface MyKernel32 extends Library {
        public MyKernel32 INSTANCE = (MyKernel32) Native.loadLibrary("Kernel32", MyKernel32.class);
    
        /** BOOL SetCurrentDirectory( LPCTSTR lpPathName ); */
        int SetCurrentDirectoryW(char[] pathName);
    }
    

    For POSIX systems:

    private interface MyCLibrary extends Library {
        MyCLibrary INSTANCE = (MyCLibrary) Native.loadLibrary("c", MyCLibrary.class);
    
        /** int chdir(const char *path); */
        int chdir( String path );
    }
    
    0 讨论(0)
  • 2020-11-22 05:38

    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 jna-posix Here's the maven info

    You can see an example of its use here (Clojure code, sorry). Look at the function chdirToRoot

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

    The working directory is a operating system feature (set when the process starts). Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:

    File f = new File ( System.getProperty("someprop"), myFilename)
    
    0 讨论(0)
  • 2020-11-22 05:40

    You can use

    new File("relative/path").getAbsoluteFile()

    after

    System.setProperty("user.dir", "/some/directory")

    System.setProperty("user.dir", "C:/OtherProject");
    File file = new File("data/data.csv").getAbsoluteFile();
    System.out.println(file.getPath());
    

    Will print

    C:\OtherProject\data\data.csv
    
    0 讨论(0)
  • 2020-11-22 05:40

    If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.

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