Home > Java > javaTutorial > Java Example - Traverse Directory

Java Example - Traverse Directory

黄舟
Release: 2017-02-13 10:26:43
Original
1583 people have browsed it

以下实例演示了使用 File 类的 dir.isDirectory() 和 dir.list() 方法来遍历目录:

/*
 author by w3cschool.cc
 Main.java
 */

import java.io.File;

public class Main {
   public static void main(String[] argv)
   throws Exception {
      System.out.println("遍历目录");
      File dir = new File("/www/java"); //要遍历的目录
      visitAllDirsAndFiles(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]));
         }
      }
   }
}
Copy after login

以上代码运行输出结果为:

遍历目录
/www/java
/www/java/Car.class
/www/java/FileUtil.class
/www/java/FileUtil.java
/www/java/HelloWorld.class
/www/java/HelloWorld.java
/www/java/HelloWorldDebug.class
/www/java/HelloWorldDebug.java
/www/java/Main$1.class
/www/java/Main.class
/www/java/Main.java
/www/java/MainClass.class
/www/java/MainClass.java
/www/java/MyClass.class
/www/java/outfilename
/www/java/test.log
Copy after login

以上就是Java 实例 - 遍历目录的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template