How to iterate over the files of a certain directory, in Java?

John Assymptoth picture John Assymptoth · Feb 7, 2011 · Viewed 211.2k times · Source

Possible Duplicate:
Best way to iterate through a directory in java?

I want to process each file in a certain directory using Java.

What is the easiest (and most common) way of doing this?

Answer

Mike Samuel picture Mike Samuel · Feb 7, 2011

If you have the directory name in myDirectoryPath,

import java.io.File;
...
  File dir = new File(myDirectoryPath);
  File[] directoryListing = dir.listFiles();
  if (directoryListing != null) {
    for (File child : directoryListing) {
      // Do something with child
    }
  } else {
    // Handle the case where dir is not really a directory.
    // Checking dir.isDirectory() above would not be sufficient
    // to avoid race conditions with another process that deletes
    // directories.
  }