Java - File Directory Listing


To list the files and directories in a directory, use the list() and listFiles() from File class.

list() and listFiles() methods do not list the files and directories recursively.

The following code lists All Files and Directories in a Directory



public class Main {
  public static void main(String[] args) {
    // Change the dirPath value to list files from your directory
    String dirPath = "C:\\";

    File dir = new File(dirPath);
    File[] list = dir.listFiles();

    for (File f : list) {
      if (f.isFile()) {
        System.out.println(f.getPath() + " (File)");
      } else if (f.isDirectory()) {
        System.out.println(f.getPath() + " (Directory)");
      }//from  w  w  w .jav a2s. co  m


Related Topic