Search code examples
javaunixnio

Why is Path.getFileName("/") inconsistent with "basename /"?


For all other paths, sun.nio.fs.UnixPath implementation (its getParent() and getFileName() methods) seems largely compatible with dirname and basename utilities, standard for any UNIX system.

Still, for the root of a UNIX file system, both Paths.get("/").getParent() and Paths.get("/").getFileName() return null's, which seems inconsistent:

$ basename /
/
$ dirname /
/

Moreover, getFileName() behaves differently from the older java.io.File implementation:

Paths.get("/").toFile().getName();

returns an empty string.

Why?


Solution

  • Why?

    Because the javadoc says so. Question already links to the javadoc, so you just have to read it:

    • getParent() - "Returns the parent path, or null if this path does not have a parent."

      The root directory doesn't have a parent, obviously.

    • getFileName() - "Returns a path representing the name of the file or directory, or null if this path has zero elements."

      There are no "elements" in the path /, where "element" is defined as the text between separators.