Changing the current working directory in Java?

前端 未结 14 1805
太阳男子
太阳男子 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: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".

提交回复
热议问题