标签:
文件删除
删除单个文件的操作很简单,如果要删除一个目录树的话,需要实现FileVisitor
接口然后递归地调用delete()
或deleteIfExists()方法。在看代码之前,需要注意一下问题。
visitFile()
方式是执行删除每个文件最好的方式。postVisitDirectory()
方法中删除目录操作。visitFileFailed()
方法来返回FileVisitResult.CONTINUE
或 TERMINATE
。 下面的程序用来删除C:\rafaelnadal
目录下所有的目录和文件。
import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; class DeleteDirectory implements FileVisitor { boolean deleteFileByFile(Path file) throws IOException { return Files.deleteIfExists(file); } @Override public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException { if (exc == null) { System.out.println("Visited: " + (Path) dir); boolean success = deleteFileByFile((Path) dir); if (success) { System.out.println("Deleted: " + (Path) dir); } else { System.out.println("Not deleted: " + (Path) dir); } } else { throw exc; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException { boolean success = deleteFileByFile((Path) file); if (success) { System.out.println("Deleted: " + (Path) file); } else { System.out.println("Not deleted: " + (Path) file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException { //report an error if necessary return FileVisitResult.CONTINUE; } } class Main { public static void main(String[] args) throws IOException { Path directory = Paths.get("C:/rafaelnadal"); DeleteDirectory walk = new DeleteDirectory(); EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); Files.walkFileTree(directory, opts, Integer.MAX_VALUE, walk); } }
标签:
原文地址:http://www.cnblogs.com/IcanFixIt/p/4919702.html