java之高效操作文件
代码:
1 import java.io.IOException; 2 import java.nio.file.FileVisitOption; 3 import java.nio.file.FileVisitResult; 4 import java.nio.file.FileVisitor; 5 import java.nio.file.Files; 6 import java.nio.file.Path; 7 import java.nio.file.Paths; 8 import java.nio.file.attribute.BasicFileAttributes; 9 import java.util.EnumSet; 10 class DeleteDirectory implements FileVisitor { 11 12 boolean deleteFileByFile(Path file) throws IOException { 13 return Files.deleteIfExists(file); 14 } 15 16 @Override 17 public FileVisitResult postVisitDirectory(Object dir, IOException exc) 18 throws IOException { 19 20 if (exc == null) { 21 System.out.println("Visited: " + (Path) dir); 22 boolean success = deleteFileByFile((Path) dir); 23 24 if (success) { 25 System.out.println("Deleted: " + (Path) dir); 26 } else { 27 System.out.println("Not deleted: " + (Path) dir); 28 } 29 } else { 30 throw exc; 31 } 32 return FileVisitResult.CONTINUE; 33 } 34 35 @Override 36 public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) 37 throws IOException { 38 return FileVisitResult.CONTINUE; 39 } 40 41 @Override 42 public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) 43 throws IOException { 44 boolean success = deleteFileByFile((Path) file); 45 46 if (success) { 47 System.out.println("Deleted: " + (Path) file); 48 } else { 49 System.out.println("Not deleted: " + (Path) file); 50 } 51 52 return FileVisitResult.CONTINUE; 53 } 54 55 @Override 56 public FileVisitResult visitFileFailed(Object file, IOException exc) 57 throws IOException { 58 //report an error if necessary 59 60 return FileVisitResult.CONTINUE; 61 } 62 } 63 64 class Main { 65 66 public static void main(String[] args) throws IOException { 67 68 Path directory = Paths.get("C:/rafaelnadal"); 69 DeleteDirectory walk = new DeleteDirectory(); 70 EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); 71 72 Files.walkFileTree(directory, opts, Integer.MAX_VALUE, walk); 73 } 74 }