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 (java.io 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)
To use apply this filter, pass an instance of it to the listFiles() method. Below is an example: