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

JavaFileDirectory

Java Problem Overview


> 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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.

You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi

Here's an example:

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
		while(it.hasNext()){
			System.out.println(((File) it.next()).getName());
		}

You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}

Solution 3 - Java

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

public static void main(String[] args) {
	File path = new File("c:/documents and settings/Zachary/desktop");
	
	File [] files = path.listFiles();
	for (int i = 0; i < files.length; i++){
		if (files[i].isFile()){ //this line weeds out other directories/folders
			System.out.println(files[i]);
		}
	}
}

Solution 4 - Java

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html">FileUtils.listFiles</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn AssymptothView Question on Stackoverflow
Solution 1 - JavaMike SamuelView Answer on Stackoverflow
Solution 2 - JavajomaoraView Answer on Stackoverflow
Solution 3 - JavaWuHoUnitedView Answer on Stackoverflow
Solution 4 - JavaAmol KatdareView Answer on Stackoverflow