Java - How to list .txt file in a directory

Posted on November 13, 2016


Instance of class that implements java.io.FilenameFilter interface is used to filter file names. In general, the listFiles() method of the java.io.File class returns all file objects in a directory. By passing the filter as arguments, we can limit the number of objects returned by the listFiles() method.

Here is an example of filtering .txt file using FilenameFilter.

FilenameFilterExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.FilenameFilter;

/**
 * @author imssbora
 */
public class FilenameFilterExample {
	public static void main(String[] args) {
		File directoryPath = new File("C:/Program Files/Java/jre1.8.0_111");
		
		//List all files and directories
		System.out.println("------------All files------------");
		for (File file : directoryPath.listFiles()) {
			System.out.println(file.getName());
		}
		
		//List text files only
		System.out.println("\n------------Text files------------");
		File[] files=directoryPath.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".txt");
			}
		});
		
		for (File file : files) {
			System.out.println(file.getName());
		}
	}
}

Output

------------All files------------
bin
COPYRIGHT
lib
LICENSE
README.txt
release
THIRDPARTYLICENSEREADME-JAVAFX.txt
THIRDPARTYLICENSEREADME.txt
Welcome.html

------------Text files------------
README.txt
THIRDPARTYLICENSEREADME-JAVAFX.txt
THIRDPARTYLICENSEREADME.txt