java遍历文件夹及所有子文件


以前写代码循环文件夹和子文件时,总是自己写递归访问,今天研究lucene时,发现JDK给我们已经提供了访问遍历的方法,上代码:

 1 String str = "C:\\Users\\LLY\\Desktop\\新建文件夹";
 2         Path path = Files.walkFileTree(Paths.get(str), new SimpleFileVisitor<Path>(){
 3 
 4             /**
 5              * 访问文件夹前执行
 6              * @param dir
 7              * @param attrs
 8              * @return
 9              * @throws IOException
10              */
11             @Override
12             public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
13                 return super.preVisitDirectory(dir, attrs);
14             }
15 
16             /**
17              * 访问文件
18              * @param file
19              * @param attrs
20              * @return
21              * @throws IOException
22              */
23             @Override
24             public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
25                 return super.visitFile(file, attrs);
26             }
27 
28             /**
29              * 访问失败执行
30              * @param file
31              * @param exc
32              * @return
33              * @throws IOException
34              */
35             @Override
36             public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
37                 return super.visitFileFailed(file, exc);
38             }
39 
40             /**
41              * 文件夹所有文件刚问完后执行
42              * @param dir
43              * @param exc
44              * @return
45              * @throws IOException
46              */
47             @Override
48             public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
49                 return super.postVisitDirectory(dir, exc);
50             }
51         });

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM