Skip to content
Advertisement

Creating a new File instance with a parent directory returns a File inside the root instead of the parent

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:usersSimonmyprogram"
}

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:usersSimonmyprogramtestfile, but instead its D:testfile.

Advertisement

Answer

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:usersSimonmyprogram"
}

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

String workingDir = System.getProperty("user.dir");
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement