File deletion
Deleting a single file is simple, and if you want to delete a directory tree, you need to implement the FileVisitor
interface and then recursively call delete()
ordeleteIfExists()方法。在看代码之前,需要注意一下问题。
- Before deleting a directory, delete the file inside.
visitFile()
The best way to do this is to delete each file.
- Because it is only possible to delete a directory if it is empty, it is recommended that you
postVisitDirectory()
remove the directory operation from the method.
- If the file does not allow access, you can use the
visitFileFailed()
method to return it or, depending on your decision FileVisitResult.CONTINUE
TERMINATE
.
- The delete process can track symbolic link files, but this is not a desirable way. Because symbolic links may point to files that are outside of the deleted domain. If you can confirm that this does not happen, or if there are other constraints preventing this from happening, you can trace the symbolic link file.
The following program is used to delete C:\rafaelnadal
all directories and files under the directory.
Importjava.io.IOException;Importjava.nio.file.FileVisitOption;ImportJava.nio.file.FileVisitResult;ImportJava.nio.file.FileVisitor;ImportJava.nio.file.Files;ImportJava.nio.file.Path;Importjava.nio.file.Paths;Importjava.nio.file.attribute.BasicFileAttributes;ImportJava.util.EnumSet;classDeleteDirectoryImplementsFilevisitor {BooleanDeletefilebyfile (Path file)throwsIOException {returnfiles.deleteifexists (file); } @Override Publicfilevisitresult postvisitdirectory (Object dir, IOException exc) throwsIOException {if(exc = =NULL) {System.out.println ("Visited:" +(Path) dir); BooleanSuccess =deletefilebyfile (Path) dir); if(Success) {SYSTEM.OUT.PRINTLN ("Deleted:" +(Path) dir); } Else{System.out.println ("Not deleted:" +(Path) dir); } } Else { Throwexc; } returnfilevisitresult.continue; } @Override Publicfilevisitresult previsitdirectory (Object dir, basicfileattributes attrs) throwsIOException {returnfilevisitresult.continue; } @Override Publicfilevisitresult visitfile (Object file, Basicfileattributes attrs) throwsIOException {BooleanSuccess =deletefilebyfile (Path) file; if(Success) {SYSTEM.OUT.PRINTLN ("Deleted:" +(Path) file); } Else{System.out.println ("Not deleted:" +(Path) file); } returnfilevisitresult.continue; } @Override Publicfilevisitresult visitfilefailed (Object file, IOException exc) throwsIOException {//Report an error if necessary returnfilevisitresult.continue; } } classMain { Public Static voidMain (string[] args)throwsIOException {Path directory= Paths.get ("C:/rafaelnadal"); DeleteDirectory Walk=Newdeletedirectory (); Enumset opts=Enumset.of (filevisitoption.follow_links); Files.walkfiletree (Directory, opts, Integer.max_value, walk); } }
Java nio.2--file or directory delete operation