Java递归列出目录下所有文件(包括子文件夹里的文件)

import java.io.FileNotFoundException;
import java.lang.*;
import java.io.File;
import java.util.Scanner;

public class Test {
    
    
    private static void SF(File file,int n)//n为文件夹层数
    {
    
    
        String str="\t".repeat(n);//输出相应数量的制表符,层次更清晰
        if(file.isDirectory())
        {
    
    
            System.out.println(str+"文件夹:"+file.getName());
            File[] fs=file.listFiles();
            System.out.println(str+'{');
            if(fs!=null)
            {
    
    
                for (File file1:fs)
                {
    
    
                    SF(file1,n+1);
                }
            }
            System.out.println(str+'}');
        }
        else if(file.isFile())
        {
    
    
            System.out.println(str+"文件:"+file.getName());
        }
    }
    private static void ShowFiles(String Path) throws FileNotFoundException {
    
    
        File file=new File(Path);
        if(file.exists())
            SF(file,0);
        else
            throw new FileNotFoundException("目录不存在!");
    }
    public static void main(String[] args)
    {
    
    
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入文件夹路径:");
        if(scanner.hasNext())
        {
    
    
            try {
    
    
                ShowFiles(scanner.next());
            } catch (FileNotFoundException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_54121864/article/details/119972138