tags:

views:

353

answers:

3

What would be the fastest way to list the names of files from 1000+ directories and sub-directories?

EDIT; The current code I use is:

import java.io.File;

public class DirectoryReader {

  static int spc_count=-1;

  static void Process(File aFile) {
    spc_count++;
    String spcs = "";
    for (int i = 0; i < spc_count; i++)
      spcs += " ";
    if(aFile.isFile())
      System.out.println(spcs + "[FILE] " + aFile.getName());
    else if (aFile.isDirectory()) {
      System.out.println(spcs + "[DIR] " + aFile.getName());
      File[] listOfFiles = aFile.listFiles();
      if(listOfFiles!=null) {
        for (int i = 0; i < listOfFiles.length; i++)
          Process(listOfFiles[i]);
      } else {
        System.out.println(spcs + " [ACCESS DENIED]");
      }
    }
    spc_count--;
  }

  public static void main(String[] args) {
    String nam = "D:/";
    File aFile = new File(nam);
    Process(aFile);
  }

}
+2  A: 

This looks fine (Recursively going through the directory) The bottleneck will be all the file i/o you need to do, optimizing your Java will not show any real improvements.

Romain Hippeau
Thank you @Romain Hippeau
Adnan
+2  A: 

Until Java 7 introduces the new java.nio.file classes (like DirectoryStream), I'm afraid what you already have will be the fastest.

R. Bemrose
Thank you @R. Bemrose
Adnan
+1  A: 

The only improvement is to get rid of static spc_count and pass spcs string as a parameter to Process.

public static void main(String[] args) {
  String nam = "D:/";
  File aFile = new File(nam);
  Process("", aFile);
}

And when doing recursive call, do

static void Process( String spcs, File aFile) {
  ...
  Process(spcs + " ", listOfFiles[i]);
  ...
}

This way you can call this method from more than 1 thread.

Alexander Pogrebnyak
Thank you for the tip @Alexander Pogrebnyak
Adnan