JavaJava Quick Tip: List All Files in a Directory by Type

Java Quick Tip: List All Files in a Directory by Type

by M. S. Shridar

As a Java developer, you may find yourself in a situation where you need to write some code to list all of the files in a folder or directory. Specifically, you may need to filter that returned list by file type. Below is a snippet of Java code that shows how to list all files in a directory by type using java.util.stream and java.nio.file:

*/

import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.nio.file.*;

public class ListOfFilesOFType
{
	public static void main(String args[])
	{
		ListOfFilesOFType listOfFilesOFType = new ListOfFilesOFType();
		listOfFilesOFType.proceed();
	}
	
	private void proceed()
	{
		final String fileExtension = "java";
		
		try (Stream files = Files.walk(Paths.get("."))) 
		{
			Collection paths = files.filter(
				f -> (f.getFileName().toString().substring(f.getFileName().toString().lastIndexOf(".") + 1))
					.equalsIgnoreCase(fileExtension)).collect(Collectors.toList());
			
			for (Path path : paths) {
				System.out.println("File: " + path.toFile());
			}
		}
		catch (IOException ioe) 
		{
			System.out.println("IOException: " + ioe);
		}
	}
}

/*

Running this code in your code editor or integrated development environment (IDE) will produce the following output:

[[email protected]]# java ListOfFilesOFType
File: .\CreateDirectory.java
File: .\ListAllFilesInFolder.java
File: .\ListOfFilesOFType.java
File: .\NetworkIntMulticastSupported.java
File: .\RuntimeHalt.java
File: .\TimeZonesInJava.java
File: .\UnderstandingFileChannels.java
File: .\UsingMath.java
File: .\UsingStackTraceElement.java
File: .\UsingZipFile.java

Note: your results may differ, based on the files in your folder or directory and the setup of your operating system files.

Latest Posts

Related Stories