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