Java基础之IO流,使用File类以树形结构打印指定文件目录

import java.io.*;

class FileTree
{
    /*
        以树形结构列举出指定目录下的文件与文件夹
    
*/
    public static void main(String[] args)  throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请键入您要查看的路径:");
        String path = br.readLine();
        if(null!=path)
        {
            printFiles(new File(path).listFiles(),0);
        }
    }
    
    public static void printFiles(File[] files,int level) throws IOException
    {
        for(File file : files)
        {
            System.out.println(printLevel(level) + "" +file.getName());
            
            if(file.isDirectory())
            {
                level++;
                printFiles(file.listFiles(),level);
            }
        }
    }
    
    public static String printLevel(int level)
    {
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<level;i++)
        {
            sb.append("|--");
        }
        
        return sb.toString();
    }
}
原文地址:https://www.cnblogs.com/cxmsky/p/2887272.html