dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Apr 23, 2021

Locating Files in a Directory with Java

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

MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date