Traverse only files under dir in Java

Description

The following code shows how to traverse only files under dir.

Example


/*from ww w.  j a v a  2 s  .  co m*/
import java.io.File;

public class Main {
  public static void main(String[] argv) throws Exception {
     visitAllFiles(new File("c:/"));
  }

  public static void visitAllFiles(File dir) {
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        visitAllFiles(new File(dir, children[i]));
      }
    } else {
      System.out.println(dir);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip