1

In my java application, I am trying to change the current working directory so that when I get the absolute path of relative File and Path instances, they are resolved with respect to the new user.dir.

I am getting inconsistent results in java 8 and java 11. Here is a simple application I created that illustrates what I am trying to do:

    public static void main(String[] args) {
        System.setProperty("user.dir", "/tmp");
        Path path1 = Paths.get("xxx");
        System.out.println(path1.toFile().getAbsolutePath());
        System.out.println(path1.toAbsolutePath());
    }

Running from my home directory in Java 8, the output is (ie- setting the user.dir has an inconsistent effect on path resolution):

/tmp/xxx
/Users/andrew.eisenberg/xxx

In Java 11, the output is (ie- setting the user.dir has no effect on path resolution):

/Users/andrew.eisenberg/xxx
/Users/andrew.eisenberg/xxx

In production, I need to use Java 8 and I need to be able to control the way I resolve relative files. How can I do this consistently?

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
  • [Changing the current working directory in Java?](https://stackoverflow.com/questions/840190/changing-the-current-working-directory-in-java) – khelwood Feb 06 '21 at 05:51
  • 1
    Just don’t do that. Keep the directory you want to use in a Path instance and use Path.resolve(). Other than that: run your program from a different user account. ;-) – Axel Feb 06 '21 at 06:38
  • That's really unfortunate. We are trying to run some unit tests in different scenarios on different machines with different directory structures. I'm sure we can find a work around, but it won't be as simple or easy to understand. – Andrew Eisenberg Feb 06 '21 at 17:01

0 Answers0