遞歸的一個典型應用就是遍歷目標文件夾,把該文件夾下的所有文件和文件夾打印或顯示出來,還可以遞歸計算目標文件夾的總大小。
1: class Program2: {3: static void Main(string[] args)4: {5: Console.WriteLine("輸入目標文件夾");6: string path = Console.ReadLine();7: FindFoldersAndFiles(path);8: Console.WriteLine("\r\n");9: Console.WriteLine("目標文件夾的總大小為:{0}個字節",GetDirectoryLength(path));10: Console.ReadKey();11: }12:13: //遞歸目標文件夾中的所有文件和文件夾14: private static void FindFoldersAndFiles(string path)15: {16: Console.WriteLine("文件夾" + path);17: //遍歷目標文件夾的所有文件18: foreach (string fileName in Directory.GetFiles(path))19: {20: Console.WriteLine("┣" + fileName);21: }22:23: //遍歷目標文件夾的所有文件夾24: foreach (string directory in Directory.GetDirectories(path))25: {26: FindFoldersAndFiles(directory);27: }28: }29:30: //遞歸計算文件夾大小31: static long GetDirectoryLength(string path)32: {33: if (!Directory.Exists(path))34: {35: return 0;36: }37:38: long size = 0;39:40: //遍歷指定路徑下的所有文件41: DirectoryInfo di = new DirectoryInfo(path);42: foreach (FileInfo fi in di.GetFiles())43: {44: size += fi.Length;45: }46:47: //遍歷指定路徑下的所有文件夾48: DirectoryInfo[] dis = di.GetDirectories();49: if (dis.Length > 0)50: {51: for (int i = 0; i < dis.Length; i++)52: {53: size += GetDirectoryLength(dis[i].FullName);54: }55: }56:57: return size;58: }59: }60:61:
以上,在遍歷目標文件夾時,使用遞歸顯示目標文件夾下所有文件夾和文件,並使用遞歸計算目標文件夾的總大小。
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
//遞歸顯示C盤下所有文件夾及其中文件
File root = new File("c:");
showAllFiles(root);
}
final static void showAllFiles(File dir) throws Exception{
File[] fs = dir.listFiles();
for(int i=0; i<fs.length; i++){
System.out.println(fs[i].getAbsolutePath());
if(fs[i].isDirectory()){
try{
showAllFiles(fs[i]);
}catch(Exception e){}
}
}
}
}
試試Quick View Folder Size吧