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.

JavaScript

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

JavaScript

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:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement