Java遞歸實現遍歷文件目錄 – JAVA編程語言程序開發技術文章

import java.io.File;
  public class ListAllPath {   
      public  void print(File mFile, int mlevel){
         for(int i = 0; i < mlevel; i++){
             System.out.print("\t");
         }
        if (mFile.isDirectory()){           
             System.out.println("<" + getPath(mFile) + ">");   
            String[] str = mFile.list();
            for (int i = 0; i < str.length; i++){
                print(new File(mFile.getPath() + "\\" + str[i]) , mlevel + 1);
            }           
         }else{
             System.out.println(getPath(mFile));
        }       
    }
   
    public  String  getPath(File mFile){
        String fullPath = mFile.getPath();
        String[] str = fullPath.split("\\\\");
         return str[str.length – 1];
     }
    
 }

 import java.io.File;
 
 public class Demo {
     public static void main(String[] args){
          ListAllPath demoTest = new ListAllPath();
          File rootFile = new File("E:\\job");
          demoTest.print(rootFile, 0);
      }
  }
 

發佈留言