John Assymptoth John Assymptoth - 2 months ago 7
Java Question

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


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

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.
  }