java之高效操作文件

2018-07-25 13:06:07来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

代码:

 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 } 
View Code

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:IDEA Save Actions插件

下一篇:java程序员基于微服务的秒杀项目实战 Spring Boot 2.0基础篇01