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

Files.isRegularFile() and Files.isDirectory()

Distinguish between regular files and directories, understanding how symbolic links are handled.

Files.isRegularFile() and Files.isDirectory()

You'll learn how to definitively determine whether a path points to a regular file or a directory, and understand how symbolic links affect these checks.

The Core Distinction

Not everything in a file system is a regular file containing data. Some paths point to directories (folders that contain other files), while others might be symbolic links, device files, or other special entities. The Files class provides two methods to make this distinction clear:

  • Files.isRegularFile(Path path, LinkOption... options) - Returns true if the path points to a regular file
  • Files.isDirectory(Path path, LinkOption... options) - Returns true if the path points to a directory

Think of these as specialized "type checkers" that go beyond just confirming existence—they tell you what kind of file system object you're dealing with.

The Symbolic Link Complication

By default, both methods follow symbolic links. If you check a symlink pointing to a directory, isDirectory() returns true for the target. To examine the symlink itself without following it, pass LinkOption.NOFOLLOW_LINKS:

Path link = Paths.get("myLink");
Path regularFile = Paths.get("document.txt");
Path directory = Paths.get("myFolder");

// Regular checks (follow symlinks)
boolean isFile = Files.isRegularFile(regularFile);      // true
boolean isDir = Files.isDirectory(directory);           // true

// Check the symlink itself, not its target
boolean linkIsFile = Files.isRegularFile(link, LinkOption.NOFOLLOW_LINKS);  // false
boolean linkIsDir = Files.isDirectory(link, LinkOption.NOFOLLOW_LINKS);     // false

These methods return false if the path doesn't exist or if the security manager denies access—never throwing an exception.

Key Takeaway: Use Files.isRegularFile() and Files.isDirectory() to distinguish between regular files and directories; control symbolic link behavior with LinkOption.NOFOLLOW_LINKS to examine links themselves rather than their targets.