On this document we will be showing a java example on how to use the list() method of File Class. This method returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of strings is returned, one for each file or directory in the directory. Names denoting the directory itself and the directory’s parent directory are not included in the result. Each string is a file name rather than a complete path.

There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.


SecurityException – If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory

Method Syntax

public String[] list()

Method Argument

Data Type Parameter Description

Method Returns

This method returns an array of String naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.


Requires Java 1.0 and up

Java File list() Example

Below is a java code demonstrates the use of list() method of File class. The example presented might be simple however it shows the behaviour of the list() method of File class. Because the list() method returns an array of String the denotes the filenames inside the directory if and only if the abstract pathname denotes directory, thus we have first put a check if the file is a directory or not. It wouldn’t make sense to just blindly list down the filenames without making sure that the pathname is a directory because the returned value would be null. Make sure to have it checked out to avoid unnecessary issues in using this method.



 * This example source code demonstrates the use of  
 * list() method of File class.

public class FileListExample {

	public static void main(String[] args) {

		// initialize File object
		File file = new File("C:javatutorialhq");

		// check if the specified pathname is directory first
			//list all files on directory
			String[] files = file.list();
			for(String s:files){

Sample Output

Below is the sample output when you run the above example.

java lang File list() example output