Home > Mobile >  Creating a new File instance with a parent directory returns a File inside the root instead of the p
Creating a new File instance with a parent directory returns a File inside the root instead of the p

Time:01-02

I have this method to get the directory that my Java program is running inside.

public File getWorkingDir() {
    Path path = Paths.get("");
    
    return path.toFile(); // Returns "D:\users\Simon\myprogram"
}

But when I create a new File instance with this directory as its parent, it returns a File inside the drive's root.

File file = new File(getWorkingDir(), "testfile");

I was expecting the absolute path of this file to be D:\users\Simon\myprogram\testfile, but instead its D:\testfile.

CodePudding user response:

Paths.get is not returning what you expect. The documentation says this about its parameters:

A Path representing an empty path is returned if first is the empty string and more does not contain any non-empty strings.

An empty path must be resolved in order to pin its location within the file system. Resolving behaves differently across the File class. The method File.getAbsolutePath, for example, resolves the empty path against the current working directory. The constructor File(File, String) resolves an empty parent against the system's default directory.

You could probably get the desired outcome by resolving the parent directory explicitly:

public String getWorkingDir() {
    Path path = Paths.get("");
    
    return path.toFile().getAbsolutePath(); // Returns "D:\users\Simon\myprogram"
}

However, the current working directory is directly available as a property:

String workingDir = System.getProperty("user.dir");
  • Related