Video in progress

Strong Middle 📁 IO and NIO

How do you check whether two `Path`s point to the same file? Why isn't `equals` enough?

Path.equals only compares the path text: data/../b.txt, ./b.txt and an absolute path are not equal. normalize() and toAbsolutePath() clean up the text, but symlinks are resolved only by toRealPath() or Files.isSameFile, which go to the disk.

📖 Answer

Path a = Path.of("b.txt");
Path b = Path.of("data/../b.txt");
a.equals(b);                                   // false
a.toAbsolutePath().equals(b.toAbsolutePath().normalize()); // true
Files.isSameFile(a, b);                        // true, asks the file system

There are three levels:

  • normalize(): text only; it removes . and ... It doesn't look at the disk, so it can wrongly collapse link/.. if link is a symlink;
  • toAbsolutePath(): prepends the working directory;
  • toRealPath(): the file must exist on disk; it resolves symlinks and returns the real path. If the file is missing: NoSuchFileException.

If the paths are equal, Files.isSameFile doesn't even go to the disk; otherwise it opens both files and compares their identifiers (device + inode on Linux). Hard links are also found to be "the same file" this way.

One more platform-dependent thing: on Windows Path.equals ignores case, on Linux it doesn't. On macOS the file system is usually case-insensitive while Path.equals is case-sensitive: Report.pdf and report.pdf are one file, but equals is false.

Where it matters: not processing the same file twice in watched directories, and security checks. For the question "is the file inside the allowed directory", apply startsWith to the result of toRealPath(), not to the raw path.