by BehindJava

How to find a file recursively in Java

Home » java » How to find a file recursively in Java

In this tutorial we are going to learn about finding a file recursively in Java.

using Java 8 we can locate a file in Java that is indicated by a starting path. It should search through a tree for a specified file. If the file is found, the location of the file should be returned.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class BehindJava {
	public static void main(String[] args) {
		try (Stream<Path> walkStream = Files.walk(Paths.get("C:\\Users\\cldee\\Downloads\\Programs"))) {
			walkStream.filter(p -> p.toFile().isFile()).forEach(f -> {
				if (f.toString().endsWith(".exe")) {
					System.out.println(f + " found!");
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Output:

C:\Users\cldee\Downloads\Programs\GrammarlyInstaller.ckzgJs7dcmbh6ihhlnaq0102.exe found!
C:\Users\cldee\Downloads\Programs\KMP64_2021.05.26.23.exe found!
C:\Users\cldee\Downloads\Programs\npp.8.1.9.1.Installer.exe found!
C:\Users\cldee\Downloads\Programs\picasa-3-9-138-150-multi-win.exe found!
C:\Users\cldee\Downloads\Programs\Teams_windows_x64.exe found!
C:\Users\cldee\Downloads\Programs\vlc-3.0.14-win64.exe found!