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.
- Open your text editor and type in the following Java statements:
The program instantiates a Fileobject 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. ThelistFilesmethod returns an array ofFileobjects. 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. - Save your file as DisplayTheContentsOfADirectory.java.
- 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.

- Type in the command to run your program and hit Enter.
Verify that the output displays all files and subdirectories in the directory you specified in the Fileconstructor parameter.
