Changing the current working directory in Java?

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

    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 );
    }
    

提交回复
热议问题