集册 Java实例教程 遍历目录下的文件和目录

遍历目录下的文件和目录

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

498
遍历目录下的文件和目录

import java.io.File;/*from n o w j a v a . c o m*/


public class Main {

  // Process all files and directories under dir

  public static void visitAllDirsAndFiles(File dir) {

    System.out.println(dir);


    if (dir.isDirectory()) {

      String[] children = dir.list();

      for (int i = 0; i < children.length; i++) {

        visitAllDirsAndFiles(new File(dir, children[i]));

      }

    }

  }


  // Process only directories under dir

  public static void visitAllDirs(File dir) {/* 来自 nowjava*/

    if (dir.isDirectory()) {

      System.out.println(dir);


      String[] children = dir.list();

      for (int i = 0; i < children.length; i++) {

        visitAllDirs(new File(dir, children[i]));

      }

    }

  }


  // Process only files under dir

  public static void visitAllFiles(File dir) {

    if (dir.isDirectory()) {

      String[] children = dir.list();

    
展开阅读全文