Java list files


 

Java list files

In this section, you will learn how to display the list of files from a particular directory.

In this section, you will learn how to display the list of files from a particular directory.

Java list files

In this section, you will learn how to display the list of files from a particular directory.

Description of code:

In the given example, we have created an object of File class and parse the directory through the constructor of the File class. Then we have called listFiles() method which actually returns the array of both the file and directory names. So in order to get only the files, we have created a condition that if the array of files contains file, then display its name.

getName(): This method of File class returns the name of file or directory.

listFiles(): This method of File class  returns an array of all the files and directories of the specified directory.

Here is the code:

import java.io.*;

class ListFiles {
	public static void main(String[] args) throws Exception {
		String text = "";
		File f = new File("C:/");
		File[] listOfFiles = f.listFiles();
		for (int j = 0; j < listOfFiles.length; j++) {
			if (listOfFiles[j].isFile()) {
				text = listOfFiles[j].getName();
				System.out.println(text);
			}
		}
	}
}

Through the above code, you can display list of files from any directory.

Output:

barbie.jpg
data.properties
data.txt
data.xls
data.xml
Hello.doc
image.jpg
image.pdf

Ads