遍歷就是把每個元素都訪問一次.比如一個二叉樹,遍歷二叉樹意思就是把二叉樹中的每個元素都訪問一次
本例演示了“文件遍歷時,指定遍歷的層數”的實現方式。
1.例子代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package com.myjava.test; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @param args */ public static void main(String[] args) { JavaTest jt = new JavaTest(); String path = "E:\\filetest" ; File file = new File(path); try { jt.getFile(file, 0 ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } int mDirLevel = 2 ; //層數 private void getFile(File file, int dirLevel) throws Exception { if (mDirLevel != - 1 && dirLevel > mDirLevel) { dirLevel = 0 ; return ; } if (file == null ) { return ; } if (file.exists()) { if (file.isFile()) { //do what? System.out.println( "file:" + file.getAbsolutePath()); } else { // 獲得當前文件夾下的所有子文件和子文件夾 File files[] = file.listFiles(); // 循環處理每個對象 if (files == null ) { return ; } for ( int i = 0 ; i < files.length; i++) { // 遞歸調用,處理每個文件對象 getFile(files[i], dirLevel + 1 ); } } } } } |
2. 測試結果:
file:E:\filetest\f.txt
file:E:\filetest\f1\新建文本文檔 - 副本.txt
file:E:\filetest\f1\新建文本文檔.txt
file:E:\filetest\f1 - 副本\新建文本文檔.txt
總結
以上就是本文關于Java編程文件遍歷之指定遍歷的層數詳細代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/liranke/article/details/38684735