• google plus

How to Display the Contents of a Directory in Java

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 Contents
    The 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 Contents
    Verify that the output displays all files and subdirectories in the directory you specified in the File constructor parameter.
Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.