Course contentsShow
← Java
Lesson 2079 of 2,87041. NIO.2 and the Path APIFree lesson

Handling Hidden Files and Special Entries

Dealing with hidden files, symbolic links, and filtering out . and .. entries when iterating directories.

Handling Hidden Files and Special Entries

You'll learn how to properly deal with hidden files, symbolic links, and directory navigation entries when working with file systems in Java.

When you iterate through directory contents using DirectoryStream or Files.list, you'll encounter files and folders that need special attention. Hidden files (like .bashrc on Linux or system files on Windows) may or may not show up depending on your needs. More importantly, you'll sometimes encounter symbolic links that point elsewhere, and on some systems, special entries like . (current directory) and .. (parent directory).

Detecting Hidden Files

Use Files.isHidden() to check if a file is marked hidden by the operating system:

Path dir = Paths.get(".");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for (Path entry : stream) {
        if (Files.isHidden(entry)) {
            System.out.println("Hidden: " + entry.getFileName());
        }
    }
}

Handling Symbolic Links

Use Files.isSymbolicLink() to identify links and decide whether to follow them or skip them:

for (Path entry : stream) {
    if (Files.isSymbolicLink(entry)) {
        System.out.println("Link: " + entry.getFileName());
        // Decide: follow or skip?
    }
}

Filtering Out . and ..

While DirectoryStream and Files.list typically don't return . and .. entries in Java, defensive code checks the file name:

for (Path entry : stream) {
    String name = entry.getFileName().toString();
    if (name.equals(".") || name.equals("..")) {
        continue; // Skip special navigation entries
    }
    // Process normal entries
}

Key Takeaway:
Always check for hidden files with Files.isHidden(), symbolic links with Files.isSymbolicLink(), and defensively filter out . and .. entries when iterating directories to avoid processing unexpected or problematic files.