How to Display the Contents of a Directory in Java

See Java: Tips and Tricks for similar articles.

Displaying the contents of a directory in Java can be accomplished using the File class. This class provides the listFiles method that returns a list of File objects for a given directory. The objects may represent files or subdirectories. To understand how to display the contents of a directory in Java, follow these four steps.

  1. Open your text editor and type in the following Java statements:Java Source for Display Directory ContentsThe program instantiates a File object and passes to the constructor the directory whose contents are to be displayed. Replace the directory shown with a directory on your file system that you know contains files and at least one subdirectory. The listFiles method returns an array of File objects. The program iterates through the array and tests each entry. A message is displayed indicating if the object is a file or a directory. The name of the entry is also displayed.
  2. Save your file as DisplayTheContentsOfADirectory.java.
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.Compile Source for Display Contents
  4. Type in the command to run your program and hit Enter.Run Display Directory ContentsVerify that the output displays all files and subdirectories in the directory you specified in the File constructor parameter.