The Java Tutorials have been written for JDK 8.Java教程是为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 Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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. NoSuchFileException
。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. 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.当您有多个线程删除文件,并且您不想仅仅因为一个线程先抛出异常而抛出异常时,静默失败非常有用。