Documentation

The Java™ Tutorials
Hide TOC
Deleting a File or Directory删除文件或目录
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)

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.Files类提供了两种删除方法。

The delete(Path) method deletes the file or throws an exception if the deletion fails. delete(Path)方法删除文件,或者在删除失败时抛出异常。For example, if the file does not exist a NoSuchFileException is thrown. 例如,如果文件不存在,将引发NoSuchFileExceptionYou 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. deleteIfExists(Path)方法也会删除该文件,但如果该文件不存在,则不会引发异常。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.当您有多个线程删除文件,并且您不想仅仅因为一个线程先抛出异常而抛出异常时,静默失败非常有用。


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