LinkOption.NOFOLLOW_LINKS for Symbolic Links
You'll learn how to control whether Java follows symbolic links when checking file existence and reading file attributes.
The Core Idea
By default, many Files methods follow symbolic links—if you check properties of a symlink, you're actually checking the target file it points to. Sometimes you need to examine the link itself rather than what it points to. That's where LinkOption.NOFOLLOW_LINKS comes in.
Think of it like a signpost pointing to a destination. Normally, when you ask "Does this lead to a real place?" you're checking if the destination exists. But sometimes you want to ask "Does this signpost itself exist?" regardless of where it points.
When This Matters
When you call Files.exists(path), Java follows symlinks by default. If the link points to a deleted file, exists() returns false even though the link itself still exists. Using LinkOption.NOFOLLOW_LINKS tells Java to check the link itself:
Path symlink = Paths.get("mylink");
// Default: follows the link, checks target
boolean targetExists = Files.exists(symlink);
// With NOFOLLOW_LINKS: checks the link itself
boolean linkExists = Files.exists(symlink, LinkOption.NOFOLLOW_LINKS);
This is crucial when reading attributes too. Without the option, you get attributes of the target file; with it, you get attributes of the symbolic link itself:
// Reads attributes of the target file
Files.readAttributes(symlink, BasicFileAttributes.class);
// Reads attributes of the symlink itself
Files.readAttributes(symlink, BasicFileAttributes.class,
LinkOption.NOFOLLOW_LINKS);
Key Takeaway: Use LinkOption.NOFOLLOW_LINKS when you need to examine or operate on symbolic links themselves rather than the files they point to, preventing Java from automatically dereferencing them.