Discuss / Java / 练习

练习

Topic source
package com.jiangzhziwei.IoExercise;

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

public class IoExercise01 {
    public static void main(String[] args) {
        System.out.println("Please input file direction: ");
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        File file = new File(input);
        try {
            PrintFiles(file, 0);
        }catch (IllegalArgumentException e){
            System.out.println("文件不存在......");
        }
    }
    static void PrintFiles(File file,int deep) {
        File printfile;
        printfile = Objects.requireNonNullElseGet(file, () -> new File("."));
        if(!printfile.exists()){
            throw new IllegalArgumentException();
        }
        StringBuilder stringBuilder = new StringBuilder();//根据子目录深度拼接空格        
            for(int i=0;i<deep;i++){
            stringBuilder.append("  ");
        }
        if (printfile.isDirectory()) {
            System.out.println(stringBuilder + printfile.getName() + "/");
            File[] files = printfile.listFiles();
            deep = deep+1;
            for (File file1:files){
                PrintFiles(file1,deep);
            }
        }else System.out.println(stringBuilder + printfile.getName());
    }
}

  • 1

Reply