file类递归,文件按层级打印

package com.epoint.file;

import java.io.File;
import java.util.Scanner;

public class printFile {
    public static void main(String[] args) {
        print(Test1.getDir(),0);
    }
    //获取输入路径
    public static File getDir(){
        Scanner sc = new Scanner(System.in);
        while(true){
            System.out.println("请输入一个文件夹路径: ");
            String dire = sc.nextLine();
            File file = new File(dire);
            if(!file.exists()){
                System.out.println("输入的路径不存在!");
            }else if(file.isFile()){
                System.out.println("请输入文件夹路径!");
            }else{
                return file;
            }
        }
    }
    //层级打印
    public static void print(File file,int lev){
        File[] files = file.listFiles();
        for (File subfile : files) {
            for (int i = 0; i <= lev; i++) {
                System.out.print("\t");
            }
            System.out.println(subfile.getName());
            if(subfile.isDirectory()){
                print(subfile,lev++);
            }
        }
    }
}

你可能感兴趣的:(java基础)