Java Reference
In-Depth Information
The following snippet of code shows how to delete a file and handle exceptions:
// Create a Path object on Windows
Path p = Paths.get("C:\\poems\\luci1.txt");
try {
// Delete the file
Files.delete(p);
System.out.println(p + " deleted successfully.");
}
catch (NoSuchFileException e) {
System.out.println(p + " does not exist.");
}
catch (DirectoryNotEmptyException e) {
System.out.println("Directory " + p + " is not empty.");
}
catch (IOException e) {
e.printStackTrace();
}
Checking for Existence of a File
The
Files
class provides two methods called
exists(Path p, LinkOption... options)
and
notExists(Path p,
LinkOption... options)
to check for the existence and non-existence of a file, respectively. Note that these two
methods are not the opposite of each other. If it is not possible to determine whether a file exists, both methods return
false
. If you need to take an action when a file exists, use the
exists()
method in your logic. If you need to take an
action when a file does not exist, use the
notExists()
method.
Copying and Moving Files
The
Files
class provides a
copy(Path source, Path target, CopyOption... options)
method to copy contents
and attributes of the specified
source
path to the specified
target
path. If the specified
source
file is a symbolic link,
the target of the symbolic link is copied, not the symbolic link. If the specified
source
file is a directory, an empty
directory at the target location is created without copying the contents of the directory. This method is overloaded.
You can use the other two versions of this method to copy all bytes from an input stream to a file and all bytes in a file
to an output stream. If the specified
source
and
target
files are the same, the
copy()
method does not do anything.
You can specify one or more of the following copy options with the
copy()
method:
•
StandardCopyOption.REPLACE_EXISTING
•
StandardCopyOption.COPY_ATTRIBUTES
LinkOption.NOFOLLOW_LINKS
If the target file already exists, the
copy()
method throws a
FileAlreadyExistsException
. You can specify the
REPLACE_EXISTING
option to replace the existing target file. If the target file is a non-empty directory, specifying the
REPLACE_EXISTING
option throws a
DirectoryNotEmptyException
. If the target file is a symbolic link and if it exists,
the symbolic link is replaced by specifying the
REPLACE_EXISTING
option, not the target of the symbolic link.
The
COPY_ATTRIBUTES
option copies the attributes of the source file to the target file. The file attributes that are
copied are highly platform- and file system-dependent. At least, the last-modified-time attribute of the source file is
copied to the target file, if supported by both file stores.
•