Java Reference
In-Depth Information
boolean Files.isDirectory(Path pathToCheck) : Tests whether the path represents a
directory.
boolean Files.isSameFile(Path firstPath, Path secondPath) : Tests whether two
paths resolve to the same location, taking into account redundant syntax and links.
Note Note that the result of performing a check on a Path is atomic and
might be violated almost immediately after you continue in your code.
Meaning that a file might be deleted, for instance, after you perform an exis-
tence check and move on with the rest of your code. This aspect can lead to
a particular kind of software bug called TOCTTOU (time of check to time of
use) and can also lead to security problems in serious cases. Therefore, never
assume too strongly that the result of your check will remain absolutely true
throughout the execution of your program, and always be ready to handle
exceptions thrown by the Files methods in a graceful manner.
Deleting Files and Folders
The next operation you can perform using the Files class is a bit more volatile, i.e. deletion. It is
possible to delete both files and folders, but for folders, the folder needs to be empty before it can be
deleted, otherwise an exception will be thrown. The following code snippet shows how the delete
method works:
try {
Files.delete(path);
} catch (NoSuchFileException x) {
// File does not exist
} catch (DirectoryNotEmptyException x) {
// The directory is not empty
} catch (IOException x) {
// File permission problem, no access
}
Note that there is also a Files.deleteIfExists(Path pathToDelete) method. This method
works in a similar manner, but will not throw an exception when the file does not exist. It just does
nothing in that case.
Copying and Moving Files and Folders
Next up, you look at two methods for copying and moving files:
Path copy(Path source, Path target, CopyOptions... options) : Copies a source
file to a target file. The options specify how the copy is performed. By default, the copy
operation will fail if the target file already exists (except when both are the same file),
unless you pass REPLACE_EXISTING as an option. If the file to copy is a directory, an empty
Search WWH ::




Custom Search