Java遍歷資料夾的兩種方法(非遞迴和遞迴)

y_keven發表於2013-08-16

import java.io.File;
import java.util.LinkedList;
public class FileSystem {
 
 public static int num;
 
    public static void main(String[] args) {
       
        long a = System.currentTimeMillis();
        //String path="c:";
        num=0;
        String[] lists={"c:","d:"};
        /*
        for(int i=0;i<lists.length;i++){
         File file=new File(lists[i]);
         scanDirRecursion(file);
        */
        for(int i=0;i<lists.length;i++){
            scanDirNoRecursion(lists[i]);
        }
       
        System.out.print("檔案總數:"+num);
        System.out.print("總耗時:");
        System.out.println(System.currentTimeMillis() - a);
    }
   

    //非遞迴
    public static void scanDirNoRecursion(String path){
     LinkedList list = new LinkedList();
        File dir = new File(path);
        File file[] = dir.listFiles();
        for (int i = 0; i < file.length; i++) {
            if (file[i].isDirectory())
                list.add(file[i]);
            else{
                System.out.println(file[i].getAbsolutePath());
                num++;
            }
        }
        File tmp;
        while (!list.isEmpty()) {
            tmp = (File)list.removeFirst();//首個目錄
            if (tmp.isDirectory()) {
                file = tmp.listFiles(); 
                if (file == null)
                    continue;
                for (int i = 0; i < file.length; i++) {
                    if (file[i].isDirectory())
                        list.add(file[i]);//目錄則加入目錄列表,關鍵
                    else{
                        System.out.println(file[i]);
                        num++;
                    }
                }
            } else {
                System.out.println(tmp);
                num++;
            }
        }
    }


 //遞迴  
 public static void scanDirRecursion(File file) {
   try {
    if (file.canRead()) {
     if (file.isDirectory()) {
      String[] files = file.list();
      if (files != null) {
       for (int i = 0; i < files.length; i++) {
        scanDirRecursion(new File(file, files[i]));
       }
      }
     } else {
      //if (file.getName().endsWith("ppt"))
       System.out.println(file);
       num++;
     }
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
 }
}
測試:

(1)遞迴: 檔案總數:189497  總耗時:39328

(2)非遞迴:檔案總數:189432 總耗時:37469

非遞迴相對要好

相關文章