How to Traverse a Folder and Find Files with Certain Extension in Java


In this example, we will use Files.walk() to traverse a folder and find files with certain extension.

Source Code

package com.beginner.examples;

import java.nio.file.*;

public class WalkFileExample {

    public static void main(String[] args){
    	// traverse the folder
    	try 
    	{
    		// traverse the folder
    		Stream path = Files.walk(Paths.get("D:\example"));
    		
    		List files = path.map(x -> x.toString())
			.filter(x -> x.endsWith(".txt")).collect(Collectors.toList());

    		// print files
    		files.forEach(System.out::println);

    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    }
}

Output:

example.txt
test.txt
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments