Get the List of Files in a Directory using Java

This Java tutorial shows how to get the list of files that are in a specific directory using Java. This tutorial will also show you how to filter the files to get only the files you are interested in.

To get the list of files, you need to create a File object for the directory. Next, you can call the listFiles() method on this File object to get the list of files contained in this directory.

File directory = new File("c:\\");
File[] files = directory.listFiles();

for (int index = 0; index < files.length; index++)
//Print out the name of files in the directory

If you don't want to get all the files in a directory, you can create a class that implements the FileFilter ( package) interface. The accept() method that you implement will specify the criteria to be used to determine if the file is returned. In our example below, the filter will only return files with "txt" for the extension.

class Filter implements FileFilter
public boolean accept(File file)
return file.getName().endsWith("txt");

To use apply this filter, pass an instance of it to the listFiles() method. Below is an example:

files.listFiles(new Filter());


getter3 said...

great ieda

Anonymous said...

cool man

Anonymous said...

What namespace is "File" part of?

Girish said...

Thank you. Works fine..

Post a Comment