Java Snippet: File and Folder List with File.list()



Learn Java with simple programming examples.

This snippet shows how to use the File.list() method to get a listing of all the files in a given folder (directory).

The folder to list is hardcoded into the program. The program uses Java’s File class to open the folder, creates a String array to store the names of the files contained in the folder, and then displays each filename on the console.

Source Code

Type (or copy) the program shown below into your computer.

Change the line:

to a valid path on your computer. An invalid path returns a NullPointerException.

Compile the program and run it.


  • Enhance the program to use the args[] parameter as the folder to list.
  • Use a try-catch block to catch a NullPointerException if an invalid folder path is specified.

Compile and Run Screenshot

Compile and execution of

Leave a Reply