集册 Java实例教程 用递归函数显示目录

用递归函数显示目录

欢马劈雪     最近更新时间:2020-01-02 10:19:05

531
用递归函数显示目录

import java.io.File;

import java.util.Scanner;

/** from 
N o w J a v a . c o m**/

public class DirList{

  static Scanner sc = new Scanner(System.in);


  public static void main(String[] args)

  {

    System.out.print("Welcome to the Directory Lister");

    do

    {

      System.out.print("\nEnter a path: ");

      String path = sc.nextLine();


      File dir = new File(path);

      if (!dir.exists() || !dir.isDirectory())

        System.out.println("\nThat directory doesn't exist.");

      else

      {
      /*
      NowJava.com
      */

        System.out.println("\nListing directory tree of:");

        System.out.println(dir.getPath());

        listDirectories(dir, "  ");

      }

    } while(askAgain());

  }


  private static void listDirectories(File dir, String indent)

  {

    File[] dirs = dir.listFiles();

    for (File f : dirs)

    {

      if (f.isDirectory())

      {

        System.out.println(indent + f.getName());

        listDirectories(f, indent + "  ");

      }

    }

  }


  private static 
展开阅读全文