File对象的使用

2021-07-25  本文已影响0人  鱿鱼炸酱面

利用File对象列出指定目录下的所有子目录和文件,并按层次打印。如果不指定参数,则使用当前目录,如果指定参数,则使用指定目录。
如:

Documents/
  word/
    1.docx
    2.docx
    work/
      abc.doc
  ppt/
  other/

实现:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Objects;

public class Main {
    public static void main(String[] args) throws IOException {
        File fs = new File(".");
        fs = fs.getCanonicalFile();
        if (args.length > 0) {
            fs = new File(args[0]);
            if (!fs.exists()) {
                throw new FileNotFoundException(args[0]);
            }
        }
        String[] splitPaths = fs.toString().split("\\\\");
        for (int i = 0; i < splitPaths.length - 1; i++) {
            System.out.println("  ".repeat(i) + splitPaths[i]);
        }
        listMyFiles(fs);
    }

    static void listMyFiles(File fs) {
        StringBuilder space = new StringBuilder();
        space.append("  ".repeat(fs.toString().split("\\\\").length - 1));
        if (fs.isDirectory()) {
            System.out.println(space + fs.getName() + "/");
            File[] dirs = {};
            try {
                dirs = Objects.requireNonNull(fs.listFiles());
            } catch (NullPointerException e) {
                System.out.println(space + "  " + "\"" + fs + "\" is not support to view!");
            }
            for (File f : dirs) {
                listMyFiles(f);
            }
        } else if (fs.isFile()) {
            System.out.println(space + fs.getName());
        }
    }
}

效果:


image.png
上一篇 下一篇

猜你喜欢

热点阅读