Discuss / Java / 支持从控制台读取输入的路径

支持从控制台读取输入的路径

Topic source

勿忘我

#1 Created at ... [Delete] [Delete and Lock User]

打印显示做了优化

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;

public class FileDemo {

  private static final AtomicReference<String> ROOT_PATH = new AtomicReference<>();

  public static void main(String[] args) throws IOException {    printDirectoryName();
  }  public static void printDirectoryName() throws IOException {    Scanner scanner = new Scanner(System.in);
    while (true) {      System.out.println("请输入要遍历打印的根目录:(退出请输入\"exit\")");
      String string = scanner.nextLine();
      if (Objects.equals(string, "exit")) {        break;
      }      File file = new File(string);
      ROOT_PATH.set(file.getAbsolutePath());
      doPrint(file);
    }  }  private static void doPrint(File file) throws IOException {    int spaceCount = spaceCount(file.getAbsolutePath());
    StringBuilder printContent = new StringBuilder();
    if (spaceCount > 0) {      printContent.append("|");
    }    IntStream.range(0, spaceCount).forEach(i -> printContent.append("--"));
    if (file.isDirectory()) {      printContent.append("📁").append(file.getCanonicalFile().getName());
      if (spaceCount == 0) {        printContent.append("[root🌳]");
      }      System.out.println(printContent);
      for (File listFile : Objects.requireNonNull(file.listFiles())) {        doPrint(listFile);
      }    } else {      printContent.append("📄").append(file.getCanonicalFile().getName());
      System.out.println(printContent);
    }  }  private static int spaceCount(String currentPath) {    if (Objects.equals(currentPath, ROOT_PATH.get())) {      return 0;
    }    return currentPath.substring(ROOT_PATH.get().length()).split("/|\\\\").length - 1;
  }}

  • 1

Reply