Thursday, September 10, 2009

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:

  • READ – Checks that the file exists and that the program has permission to read the file. On UNIX systems, this option tests the file owner READ bit
  • WRITE – Checks that the file exists and that the program has permission to write to the file. On UNIX systems, this tests the file owner WRITE bit
  • EXECUTE – Checks that the file exists and that the program has permission to execute the file. For directories on UNIX file systems, the execute bit must be set in order to access files or subdirectories. On UNIX system, this option tests the file owner EXECUTE bit

If checkAccess is called with no argument, the file's existence is checked. If all you need to do is verify the file's existence, you could use the exists or notExists methods, as 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 Basic File Attributes, this code snippet is extended 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 determine if they locate the same file on the file system. For example:

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;
}

No comments: