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

Files.isReadable(), isWritable(), and isExecutable()

Test file permissions to determine if the current process can read, write, or execute a file.

Files.isReadable(), isWritable(), and isExecutable()

What you'll learn: How to check whether your program has permission to read, write, or execute a specific file before attempting the operation.

Understanding File Permissions

Just because a file exists doesn't mean your program can do anything with it. Operating systems enforce file permissions that control which users and processes can read, write, or execute files. Before attempting file operations, it's wise to check whether your program has the necessary permissions.

Think of it like building access: a door might exist, but you need the right keycard (permissions) to open it, write on the whiteboard inside, or use the equipment in that room.

The Permission Test Methods

The Files class provides three methods to test permissions from the current process's perspective:

  • Files.isReadable(Path path) – Returns true if the file exists and your program can read its contents
  • Files.isWritable(Path path) – Returns true if the file exists and your program can modify it
  • Files.isExecutable(Path path) – Returns true if the file exists and your program can execute it (relevant for scripts and binaries)
Path configFile = Paths.get("config.txt");

if (Files.isReadable(configFile)) {
    String content = Files.readString(configFile);
    // Process content...
}

if (Files.isWritable(configFile)) {
    Files.writeString(configFile, "new data");
}

Path script = Paths.get("script.sh");
if (Files.isExecutable(script)) {
    // Safe to execute
}

Important Notes

These methods test permissions for the current process, not universally. A file might be readable by you but not by another user. If a file doesn't exist, all three methods return false.

Key Takeaway: Use Files.isReadable(), isWritable(), and isExecutable() to verify your program has the necessary permissions before attempting file operations, preventing runtime exceptions and improving error handling.