Friday, May 13, 2011

List Files in a Directory

The following Java example returns an ArrayList of only those files that have a .csv extension.

public static ArrayList listFiles(String dirName) {
 ArrayList al = new ArrayList();
 File dir = new File(dirName);

 String[] children = dir.list(filter);
 if (children == null) {
//Either dir does not exist or is not a directory
  }
 else {
  for (int i = 0; i < children.length; i++) {
  // Add the file name to ArrayList
   al.add(children[i]);
  }
 }
  return al;
}

// Create an an inner class that implements the FilenameFilter interface.
    static FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith("csv");
        }
    };

To list all files in the directory use the list() method without arguments.

The code is based on the Java Developers Almanac .

No comments:

Post a Comment