【问题标题】:How to do a recursive tree of folders and files?如何做文件夹和文件的递归树?
【发布时间】:2018-05-27 19:17:55
【问题描述】:

我编写了一个程序,它接收一个文件作为第一个参数并打印出一棵树,但我希望它比仅检查输入文件/文件夹包含的子目录或文件更深入。

import java.io.File;

public class DN12 {
    public static void main(String[] args)throws Exception {
        File file = new File(args[0]);
        String fPath = file.getPath();
        System.out.println(fPath);
        File[] paths = file.listFiles();
        for(int i=0; i<paths.length; i++) {
            String path2 = paths[i].getPath();
            String[] path3 = path2.split("/");
            System.out.println("  |___"+path3[path3.length-1]);
        }  
    }
}

示例输入:

/p2/sources

我的输出:

/p2/viri
  |___sun.txt
  |___tree
  |___abc.txt

预期输出:

/p2/viri
  |___sun.txt
  |___tree
  |  |___.DS_Store
  |  |___dir1
  |  |  |___dir11
  |  |  |  |___b.txt
  |  |  |___a.txt
  |  |___src
  |  |  |___predavanja11
  |  |  |  |___TestDrzava.java
  |  |  |  |___Dnevi.java
  |  |  |  |___Drzave.java
  |  |  |  |___Oseba.java
  |  |  |  |___Delitelji.java
  |  |  |  |___Drzava.java
  |  |  |  |___Meseci.java
  |  |  |  |___TestOseba.java
  |  |___dir2
  |  |  |___dir21
  |  |  |___dir22
  |  |  |  |___e.txt
  |  |  |___d.txt
  |___abc.txt

【问题讨论】:

标签: java


【解决方案1】:

您需要定义一个递归方法。在 javaish 伪代码中。

public static void listFiles(File f, int spaces) {
    String s = <BUILD STRING OF SPACES>;
    System.out.println(s + <YOUR_FILE_PRINT>);
    // print current file
    for (File f : f.listPaths()) {
        // Do printing.
        if (f.isDirectory()) {
            listFiles(f, spaces + 2); // recursive call
        }
    }
}

递归方法需要有一个基本情况。在这种情况下,我们只有在它是一个目录并且堆栈总是展开时才会递归。

【讨论】:

  • @Pshemo 谢谢。我没有意识到它不可用。
【解决方案2】:

你可以这样做:

public static void main(String[] args) {
    displayDirRecursively("sources", 0);
}

public static void displayDirRecursively(String directory, int depth) {
    File file = new File(directory);
    if (depth > 0) {
        for (int i = 0; i < depth; i++) {
            System.out.print("   ");
        }
        System.out.print("|__");
    }
    System.out.println(file.getName());
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            displayDirRecursively(files[i].getPath(), depth + 1);
        }
    }
}

【讨论】:

    【解决方案3】:
    public class Main {
    
      public static void main(String[] args) {
        new Main().fooCursive(new File(System.getProperty("user.dir")));
    
      }
    
      public void fooCursive(File file) {
        System.out.println(file.getName());
        if (file.exists() && file.isDirectory()) {
          Stream.of(file.listFiles()).forEach(subfile -> fooCursive(subfile));
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-11
      相关资源
      最近更新 更多