dcsimg
 

Locating Files in a Directory with Java

Friday Apr 23rd 2021 by MS Sridhar
Article Image

In this Java programming tutorial quick tip, we learn how to use Java utility packages to locate files in a directory.

How to Locate Files in a Directory Using Java

In this Java programming tutorial quick tip, we learn how to use Java utility packages to locate files in a directory.

Java has utility packages that help you navigate file hierarchy and file structures. This is an example of one way to locate files in a directory - there are multiple methods that can further improve your search.

Java code sample:

*/

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

public class FindListOfFiles{

	public static void main(String []args){
		FindListOfFiles findListOfFiles = new FindListOfFiles();
		findListOfFiles.proceed();
	}

	private void proceed()
	{
	    String lookUpDir = ".";
	    String lookUpFileName = "FindListOfFiles.java";
	    
		try (Stream files = Files.walk(Paths.get(lookUpDir)))
		{
		    Collection path = 
		        files.filter(f -> f.getFileName().toString().equals(lookUpFileName)).collect(Collectors.toList());
				//In case you want to search using file name extensions, use the following
				//files.filter(f -> f.getFileName().toString().endsWith(".java")).collect(Collectors.toList());
		    
		    for (Path fileNameWithPath : path)
                System.out.println(fileNameWithPath);
		}
		catch(Exception e)
		{
		    System.out.println("Exception: " + e);
		}

	}
}

/*

This provides the following output: $java FindListOfFiles ./FindListOfFiles.java

Home
Mobile Site | Full Site