输入路径(包括盘符),打印层级目录(隐藏文件也会打印出来)

学习笔记,记录一下

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

public class Test4 {
    /*
     * 打印一个文件夹下的所有文件和文件夹,需要打印出层级目录(隐藏文件也会打印出来)
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        File dir = getDir(); // 获取文件夹路径
        System.out.println(dir);
        printLevFile(dir, 1);
    }

    public static File getDir() {
        try (Scanner cin = new Scanner(System.in);) {
            System.out.println("请输入一个文件夹路径");
            while (true) {
                String line = cin.nextLine();
                File dir = new File(line);
                if (!dir.exists()) {
                    System.out.println("不存在!重输:");
                } else if (dir.isFile()) {
                    System.out.println("输入的不是文件夹,请重新输入:");
                } else {
                    return dir;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null; 
    }

    /*
     * 打印层级目录 1.void 2.参数列表File dir
     */
    public static void printLevFile(File dir, int lev) throws Exception {
        File[] subFiles = dir.listFiles();
        if (subFiles != null) {// 路径仅仅只有盘符可能有dir为空的情况
            for (File subFile : subFiles) {
                for (int i = 0; i < lev; ++i) {
                    System.out.print("-");
                }
                //Thread.sleep(500);
                System.out.println(subFile);
                if (subFile.isDirectory()) {
                    printLevFile(subFile, lev + 1);
                }
            }
        } else {
            System.out.println("此时为空,注意查看!");
            Thread.sleep(10000); // 暂停10s查看
        }
    }
}

自己调试,暂停用延时,访问到-f:\System Volume Information是会有java.lang.NullPointerException,所以用if和else判断,方便观察

========================================Talk is cheap, show me the code=======================================

猜你喜欢

转载自blog.csdn.net/qq_34115899/article/details/80819109