Handling Exceptions
Errors are bound to occur when interacting with the file system. Numerous errors can occur, and among the most common errors are the following:
- A required file or directory does not exist in the file system.
- Permissions to access a file are incorrect.
A majority of the static methods in the Files class throw a java.io.IOException that acts as the catchall for various I/O errors. Its subclass, java.nio.file.NoSuchFile-Exception, unequivocally makes clear the cause of the exception. As these exceptions are checked exceptions, code using these methods should diligently handle these exceptions with either a try-catch-finally construct or a throws clause.
For brevity, the exception handling may be omitted in some code presented in this chapter.
Handling Symbolic Links
The methods of the Files class are savvy with regard to symbolic links. Following of symbolic links is typically indicated by specifying or omitting the constant LinkOption.NOFOLLOW_LINKS for the variable arity parameter of the method (see below).
Specifying Variable Arity Parameters
Many static methods in the Files class have a variable arity parameter. Such a parameter allows zero or more options to customize the operation implemented by the method. For example, the following method takes into consideration symbolic links depending on whether or not the variable arity parameter options is specified:
// Method header:
static boolean exists(Path path, LinkOption… options) // Variable arity param.
// Method calls:
Path path = Path.of(“alias”);
boolean result1 = Files.exists(path); // Follow symbolic links.
boolean result2 = Files.exists(path,
LinkOption.NOFOLLOW_LINKS); // Do not follow symbolic links.
Executing Atomic Operations
Certain file operations can be performed as atomic operations. Such an operation guarantees the integrity of any resource it uses. It runs independently and cannot be interrupted by other operations that might be running concurrently. See the atomic move operation (p. 1305).
Leave a Reply