0

I would like to set current path in Java using java.nio.file.Path.

Is that possible?

I know that is possible get current path using this:

public Path getCurrentPath() {
    Path workingDirectory = Paths.get(".").toAbsolutePath().normalize();
    return workingDirectory;
}
Manjunath Ballur
  • 6,287
  • 3
  • 37
  • 48
dfsdf
  • 11
  • 1

1 Answers1

2

There is no equivalent to the cd command on the operating system inside a java application (see general information about current directory.

The current directory for the JVM is the directory from which you start it. This information is stored in the system property user.dir. java.io.File and java.nio.file.Path use this information as current directory.

You could override this by passing -Duser.dir=... as JVM startup option. Which would change the current directory for File and Path.

Changing this system property at runtime with System.setProperty("user.dir") actually would not change the current directory. It would e.g. have an impact on what File assume as the current directory. Path still would use the directory from which the JVM was started.

For an earlier SO post Why does this autorun-cmd registry hack affect a java/maven process? I had set up a small project to demonstrate the effects.

Community
  • 1
  • 1
SubOptimal
  • 22,518
  • 3
  • 53
  • 69