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.
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. The
listFilesmethod returns an array of
Fileobjects. 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.