Changing the current working directory in Java?

前端 未结 14 1507
太阳男子
太阳男子 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条回答
  •  -上瘾入骨i
    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

提交回复
热议问题