How to iterate over files of a specific directory in Java?

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

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

What is the easiest (and most common) way to do this?

+72
java file directory
Feb 07 2018-11-11T00:
source share
4 answers

If you have a 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. } 
+130
Feb 07 2018-11-11T00:
source share

I think there are so many ways to do what you want. Here is the path I use. Using the commons.io library commons.io you can commons.io over 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 is 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 extensions if you want to filter. Example: {".xml",".java"}

+27
Feb 07 2018-11-11T00:
source share

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

Instead of printing the file name using System.out.println, you should put your own code to work with 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]); } } } 
+6
Feb 07 '11 at 1:00
source share

Use java.io.File.listFiles
Or
If you want to filter the list before iteration (or in a more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

+3
Feb 07 '11 at 1:01
source share



All Articles