Share on Google+Share on Google+

Java list files

Advertisement
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

Advertisements

Advertisement

Posted on: April 27, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.