JAVA显示文件夹的结构

发布时间:2013-01-30 08:47:26

java列出目录结构:


import java.io.*;
public class FolderList {   
   
    /**  
     * 显示文件结构  
     */   
    private static int spaceNum = 3;   
    public static void main(String[] args) {   
           
        File folder = new File("c:/java");   
        System.out.println(folder.getName());//打印根目录    
        showFiles(spaceNum,1,folder.listFiles());   
    }   
       
    //显示文件:深度优先遍历(deepth为文件夹深度)    
    private static void showFiles(int sapce,int deepth,File[] files) {   
        StringBuffer spaceStr = new StringBuffer();   
        int tmp = deepth;//保存输入的deepth值,放在deepth--操作丢失数据    
        //添加空格 ,树形结构调整    
        for(int i=0;i< sapce;i++){   
            if((i%spaceNum==0)&&(deepth>=0)&&(i!=0)){   
                spaceStr.append("|");   
                deepth-- ;   
            }   
            spaceStr.append(" ");   
               
        }   
        spaceStr.append("|─");   
        for(File file : files){   
            System.out.println(spaceStr+file.getName());   
            //如果是文件夹,继续遍历    
            if(file.isDirectory()){   
                showFiles(sapce+spaceNum,tmp+1,file.listFiles());   
            }   
        }   
           
    }   
   
}  
D:\java>java   FolderList
HySnapDX
   |─HySnapDX
   |   |─HySnapDX
   |   |   |─1.bmp
   |   |   |─2.bmp
   |   |   |─3.bmp
   |   |   |─4.bmp
   |   |   |─5.bmp
   |   |   |─6.bmp
   |   |   |─7.bmp
   |   |   |─8.bmp
   |   |   |─dxsnap.dll
   |   |   |─file_id.diz
   |   |   |─hsdx.cnt
   |   |   |─hsdx.exe
   |   |   |─hsdx.hlp
   |   |   |─hsdx.ini
   |   |   |─HSDX.lic
   |   |   |─HShelper.dll
   |   |   |─HSPro
   |   |   |   |─hspro.dll
   |   |   |   |─lfavi70n.dll
   |   |   |   |─lfbmp70n.dll