Java file list()


 

Java file list()

This section demonstrates you the use of method list().

This section demonstrates you the use of method list().

Java file list()

This section demonstrates you the use of method list().

You can get the list of files and directories in two ways. Either by using listFiles() method or by list() method. Here we will discuss the method list() of File class.

You can see in the given example, we have created an instance of File class and specify the directory path in the constructor of the File class. Then we have called the list( ) method through the File object. This method will return the array of string consisting of files and subdirectories of the given directory.

list(): This method of Files class returns an array of strings naming the files and directories in the directory.

Here is the code:

import java.io.*;

public class FileList {
	public static void main(String[] args) {
		File f = new File("C:/Text");
		String str[] = f.list();
		for (int i = 0; i < str.length; i++) {
			System.out.println(str[i]);
		}
	}
}

Through the above code, it will be easier for you to understand the use of method list().

Ads