Java I/O How to - Get all files and folders under a certain folder and save them to a set








Question

We would like to know how to get all files and folders under a certain folder and save them to a set.

Answer

/*from w  w  w  . j  a v a2  s .  c  o  m*/
import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class Main {
  public static void main(String[] argv) {
    Set<File> all = new HashSet<File>();
    getAllFileAndFolder(new File("c:\\"), all);
  }

  public static void getAllFileAndFolder(File folder, Set<File> all) {
    all.add(folder);
    if (folder.isFile()) {
      return;
    }
    for (File file : folder.listFiles()) {
      all.add(file);
      if (file.isDirectory()) {
        getAllFileAndFolder(file, all);
      }
    }
  }
}