Java Reference
In-Depth Information
Now the parent directory is always created before attempting to create the file. If the parent already exists,
then the createDirectories() method does nothing. The NoSuchFileException exception now is not
thrown, but it is still possible that the createFile() method throws an exception of type FileAlreadyEx-
istsException . You can see this happen if you execute the preceding fragment twice.
Deleting Files and Directories
The Files class defines a delete() method that deletes a file or a directory. A directory has to be empty
before it can be deleted. Attempting to delete a directory that is not empty results in the delete() meth-
od throwing an exception of type java.nio.file.DirectoryNotEmptyException . For example, after ex-
ecuting the fragment in the previous section that creates junk.txt , the following code throws the Direct-
oryNotEmptyException exception:
Path path = Paths.get("D:/Garbage/dir/dir1/dir2/junk.txt");
try {
Files.delete(path.getParent()); // Delete parent directory
} catch(DirectoryNotEmptyException e) {
System.err.println("Directory not deleted.\n"+ e);
} catch(IOException e) {
System.err.println(e);
}
However, if you first delete the file, you are able to delete the directory:
Path path = Paths.get("D:/Garbage/dir/dir1/dir2/junk.txt");
try {
Files.delete(path); // Delete file
Files.delete(path.getParent()); // Delete parent directory
} catch(DirectoryNotEmptyException e) {
System.err.println("Directory not deleted.\n"+ e);
} catch(IOException e) {
System.err.println(e);
}
This fragment deletes the junk.txt file and then deletes the dir2 directory. The directory
D:\Garbage\dir\dir1 remains.
If you attempt to delete a file or directory that does not exist using the delete() method, an exception
of type NoSuchFileException is thrown. You can avoid this possibility by using the deleteIfExists()
method in the Files class. When you are deleting a file using this method, no exception is thrown if the file
or directory is not there but you can still get the DirectoryNotEmptyException exception thrown when
you use it to delete a directory.
WARNING Always take particular care when programming delete operations. Errors can be
catastrophic if they result in essential files being removed.
Search WWH ::




Custom Search