A browser with JavaScript enabled is required for this page to operate properly.
Documentation

The Java™ Tutorials
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)
« PreviousTrailNext »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
See Dev.java for updated tutorials taking advantage of the latest releases.
See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Deleting a File or Directory

You can delete files, directories or links. With symbolic links, the link is deleted and not the target of the link. With directories, the directory must be empty, or the deletion fails.

The Files class provides two deletion methods.

The delete(Path) method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. You can catch the exception to determine why the delete failed as follows:

try {
 Files.delete(path);
} catch (NoSuchFileException x) {
 System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
 System.err.format("%s not empty%n", path);
} catch (IOException x) {
 // File permission problems are caught here.
 System.err.println(x);
}

The deleteIfExists(Path) method also deletes the file, but if the file does not exist, no exception is thrown. Failing silently is useful when you have multiple threads deleting files and you don't want to throw an exception just because one thread did so first.

« PreviousTrailNext »

Previous page: Checking a File or Directory
Next page: Copying a File or Directory

AltStyle によって変換されたページ (->オリジナル) /