Trail: Essential Classes
Lesson: Basic I/O
Section: File I/O (featuring NIO.2)
Checking a File or Directory
Home Page > Essential Classes > Basic I/O
Checking a File or Directory

Checking File Accessibility

You have a Path instance representing a file or directory, but does that file exist on the file system? Is it readable? writable? executable?

To verify that a file exists and that the program can access it as needed, you can use the checkAccess(AccessMode...) method. The varargs argument can be any combination of these AccessMode options:

If checkAccess is called with no argument, the file's existence is checked. If all you want to do is to verify the file's existence, you might want to use the exists or notExists methods, described in Verifying the Existence of a File or Directory.

The following code snippet verifies that a particular file exists, and that the program has the ability to execute the file. Note that this snippet assumes that the Path is a file and not a directory. You can use the java.nio.file.attributes package to learn more about the Path — is it a directory? a regular file? a symbolic link? Later, in the Basic File Attributes section, we extend this code snippet to verify that the Path locates a regular executable file and only a regular executable file.

import static java.nio.file.AccessMode.*;
  
Path file = ...;
try {
    file.checkAccess(READ, EXECUTE);
} catch (IOException x) {
    //Logic for error condition...
    return;
}

//Logic for executable file...

Note: Once the checkAccess method completes, there is no guarantee that the file can be accessed. A common security flaw in many applications is to perform a check and then access the file. For more information, use your favorite search engine to look up TOCTTOU (pronounced TOCK-too).

Checking Whether Two Paths Locate the Same File

When you have a file system that uses symbolic links, it is possible to have two different paths that locate the same file. The isSameFile(Path) method compares two paths to see if they locate the same file on the file system.

Path p1 = ...;
Path p2 = ...;

try {
    if (p1.isSameFile(p2)) {
        //Logic when the paths locate the same file
    }
} catch (IOException x) {
    //Logic for error condition...
    return;
}
Previous page: File Operations
Next page: Deleting a File or Directory