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 theseAccessMode
options:
READ
— Checks that the file exists and that the program has permission to read the file. (On UNIX, this tests the file owner READ bit.)WRITE
— Checks that the file exists and that the program has permission to write the file. (On UNIX, 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, this tests the file owner EXECUTE bit.)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 theexists
ornotExists
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 thejava.nio.file.attributes
package to learn more about thePath
— 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 thePath
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 thecheckAccess
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 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 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; }