Java - File Directory Listing

Introduction

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

Demo

import java.io.File;

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)");
      }/*  w w  w . j a  v a 2  s.  co  m*/
    }
  }
}

Result

Related Topic