开发者

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

开发者 https://www.devze.com 2023-02-08 18:02 出处:网络
This question already has answers here: Closed 12 years ago. The community reviewed whether to reopen this question 1 year ago and left it closed:
This question already has answers here: Closed 12 years ago.

The community reviewed whether to reopen this question 1 year ago and left it closed:

Original close reason(s) were not resolved

开发者_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?


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


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


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]);
        }
    }
}


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. FileUtils.listFiles

0

精彩评论

暂无评论...
验证码 换一张
取 消