Checking File Accessibility
You have a
Pathinstance 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 theseAccessModeoptions:
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 bitWRITE– 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 bitEXECUTE– 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 bitIf
checkAccessis 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 theexistsornotExistsmethods, 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
Pathis a file and not a directory. You can use thejava.nio.file.attributespackage to learn more about thePath: is it a directory? A regular file? A symbolic link? Later, in Basic File Attributes, this code snippet is extended to verify that thePathlocates 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 thecheckAccessmethod 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 upTOCTTOU(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; }