Alex Rivera | Logout

List all files from a directory recursively with Java

Asked 2010-03-28T21:26:32.870
101

I have this function that prints the name of all the files in a directory recursively. The problem is that my code is very slow because it has to access a remote network device with every iteration.

My plan is to first load all the files from the directory recursively and then after that go through all files with the regex to filter out all the files I don't want. Is there a better solution?

public static printFnames(String sDir) {
    File[] faFiles = new File(sDir).listFiles();
    for (File file : faFiles) {
        if (file.getName().matches("^(.*?)")) {
            System.out.println(file.getAbsolutePath());
        }
        if (file.isDirectory()) {
            printFnames(file.getAbsolutePath());
        }
    }
}

This is just a test. Later on I'm not going to use the code like this; instead I'm going to add the path and modification date of every file which matches an advanced regex to an array.

Edit
Report

1 Answer

0

The more efficient way I found in dealing with millions of folders and files is to capture a directory listing through a DOS command in some file and parse it.

Once you have parsed the data then you can do analysis and compute statistics.

answered 2011-12-09T12:29:55.107

Your Answer