Skip to Content

List contents of a directory

  1. /*
  2.   List contents of a directory
  3.   This Java example shows how list contents(files and sub-directories) of a directory
  4.   using list method of Java File class.
  5. */
  6.  
  7. import java.io.*;
  8.  
  9. public class ListContentOfDirectory {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create file object
  14.     File file = new File("C://FileIO");
  15.    
  16.     /*
  17.      * To list contents of a directory use,
  18.      * String[] list() method of Java File class.
  19.      *
  20.      * This method returns an array of Strings containing name of files and
  21.      * sub-directories. It reuturns an empty array, if directory is empty,
  22.      * and null if file does not denotes a directory.
  23.      */
  24.    
  25.      String[] files = file.list();
  26.    
  27.      System.out.println("Listing contents of " + file.getPath());
  28.      for(int i=0 ; i < files.length ; i++)
  29.      {
  30.        System.out.println(files[i]);
  31.      }
  32.   }
  33. }
  34.  
  35. /*
  36. Output would be
  37. Listing contents of C:\FileIO
  38. demo.txt
  39. HiddenDemo.txt
  40. JavaTemp10351.javatemp
  41. JavaTemp40534.javatemp
  42. ReadText.txt
  43. */