遞歸例子

要獲取某個文件夾下所有文件的總記錄(包括子文件夾中的文件)

public int getFileCount(File path) {
int count = 0;
if (path.isFile()) { //如果是文件
count++;
} else if (path.isDirectory()) { //如果是文件夾
for (File f : path.listFiles()) { //遍歷文件夾下的所有子文件
count += getFileCount(f); //遞歸獲得子文件夾的文件數
}
}
return count;
}

轉載請註明來源:http://topic.csdn.net/u/20120516/10/b74ac11d-6a9b-46ec-8dd1-fe5232c60ac9.html?45641 引用二樓

歡迎加關注


ps:關於遞歸

遞歸算法:在函數或子過程的內部,直接或者間接地調用自己的算法。

遞歸的一般模式:

public int getFileCount(File path) {
int count = 0;
if (path.isFile()) { //(邊界條件及必要操作)
count++;
} else if (path.isDirectory()) { //不滿足此邊界條件的
for (File f : path.listFiles()) { //(重複的操作,相同邏輯);
count += getFileCount(f);
}
}
return count;
}  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章