The Java Files utility class
The Java java.nio.file.Files class provides a number of utility methods for performing
basic operations such as loading, moving and copying files. The methods generally
have the following features:
- they are generally static methods,
with the first parameter being a Path object
providing the location of the file in question;
- they throw exceptions (generally an IOException) to indicate
when an error occors (whereas older Java I/O methods tended to
return false or null, making it easy to forget to check for errors,
and not necessarily indicating what the actual error was);
- they often allow relevant options to be set, such as whether file operations
can replace existing data or whether the path in question follows symbolic links.
Exceptions thrown by Files methods generally include errors where the account running the Java program
does not have relevant access permissions. This is generally more useful than older methods such as File.delete() which
would simply fail silently and required the programmer to remember to check the return value (and often made it difficult if even
possible to query the actual reason for the failure).
Some of the most useful methods of the Files are listed in the table below.
Method | Function | Comments |
Files.isReadable() Files.isWritable() Files.isExecutable() | Checks the relevant access permissions on a given file. | These methods also check that the given file actually exists. |
Files.copy() | Copies a source file to a given destination. | An attempt to copy over an existing file will fail unless StandardCopyOptions.REPLACE_EXISTING is passed in as an option. |
Files.move() | Moves a source file to a given destination. | As with copy(), an attempt to move over an existing file will fail unless StandardCopyOptions.REPLACE_EXISTING is passed in. |
Files.delete() | Deletes the given file. | |
Files.isSameFile() | Determines whether two given paths actually refer to the same file. | Given the presence of symbolic links or relative directory specifies (. and ..), two paths that are not strictly equal could actually refer to the same file. This method is used to detect such a case. |
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.