What you want is File.listFiles(FileNameFilter filter).

That will give you a list of the files in the directory you want that match a certain filter.

The code will look similar to:

Copy// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});
Answer from jjnguy on Stack Overflow
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ java files.find examples
Java Files.find examples - Mkyong.com
December 2, 2020 - Java 8 `Files.find` examples to find files by filename, file size, and last modified time.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ tutorial โ€บ essential โ€บ io โ€บ find.html
Finding Files (The Javaโ„ข Tutorials > Essential Java Classes > Basic I/O)
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{java,class}"); Path filename = ...; if (matcher.matches(filename)) { System.out.println(filename); } Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.
Top answer
1 of 10
33

you can try something like this:

import java.io.*;
import java.util.*;
class FindFile 
{
    public void findFile(String name,File file)
    {
        File[] list = file.listFiles();
        if(list!=null)
        for (File fil : list)
        {
            if (fil.isDirectory())
            {
                findFile(name,fil);
            }
            else if (name.equalsIgnoreCase(fil.getName()))
            {
                System.out.println(fil.getParentFile());
            }
        }
    }
    public static void main(String[] args) 
    {
        FindFile ff = new FindFile();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the file to be searched.. " );
        String name = scan.next();
        System.out.println("Enter the directory where to search ");
        String directory = scan.next();
        ff.findFile(name,new File(directory));
    }
}

Here is the output:

J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load
2 of 10
18

Using Java 8+ features we can write the code in few lines:

protected static Collection<Path> find(String fileName, String searchDirectory) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(f -> f.getFileName().toString().equals(fileName))
                .collect(Collectors.toList());

    }
}

Files.walk returns a Stream<Path> which is "walking the file tree rooted at" the given searchDirectory. To select the desired files only a filter is applied on the Stream files. It compares the file name of a Path with the given fileName.

Note that the documentation of Files.walk requires

This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.

I'm using the try-resource-statement.


For advanced searches an alternative is to use a PathMatcher:

protected static Collection<Path> find(String searchDirectory, PathMatcher matcher) throws IOException {
    try (Stream<Path> files = Files.walk(Paths.get(searchDirectory))) {
        return files
                .filter(matcher::matches)
                .collect(Collectors.toList());

    }
}

An example how to use it to find a certain file:

public static void main(String[] args) throws IOException {
    String searchDirectory = args[0];
    String fileName = args[1];
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName);
    Collection<Path> find = find(searchDirectory, matcher);
    System.out.println(find);
}

More about it: Oracle Finding Files tutorial

๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 545494 โ€บ java โ€บ find-file-file-Java
How to find a file (any file) in Java (Java in General forum at Coderanch)
July 15, 2011 - At least i can tell you how to get the system drive. parseAllfiles() is the custom method you have to write to parse all the files & folders present in the system drive. Karan - Welcome to the Ranch ... Thanks Jai .. I think it will surely help me out .. If not i will again raise question ... Jai I am getting only the name of drive in which java is installed and not the all directories/drives Please help
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Find elsewhere
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javaexamples โ€บ dir_search.htm
How to search all files inside a directory in Java
import java.io.File; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { System.out.println("Enter the path to folder to search for files"); Scanner s1 = new Scanner(System.in); String folderPath = s1.next(); File folder = new File(folderPath); if (folder.isDirectory()) { File[] listOfFiles = folder.listFiles(); if (listOfFiles.length < 1)System.out.println( "There is no File inside Folder"); else System.out.println("List of Files & Folder"); for (File file : listOfFiles) { if(!file.isDirectory())System.out.println( file.getCanonicalPath().toString()); } } else System.out .println("There is no Folder @ given path :" + folderPath); } }
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-search-a-file-in-a-directory-in-java
How to search a file in a directory in java
February 8, 2021 - In order to search for a file you need to compare the name of each file in the directory to the name of the required file using the equals() method. ... import java.io.File; import java.util.Arrays; import java.util.Scanner; public class Example { public static void main(String[] argv) throws ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ javaexamples โ€บ dir_search_file.htm
How to search for a file in a directory using Java
February 8, 2021 - Following example displays all the files having file names starting with 'b'. import java.io.*; public class Main { public static void main(String[] args) { File dir = new File("C:"); FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("b"); } }; String[] children = dir.list(filter); if (children == null) { System.out.println("Either dir does not exist or is not a directory"); } else { for (int i = 0; i< children.length; i++) { String filename = children[i]; System.out.println(filename); } } } }
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ i/o โ€บ how to find a file in directory in java
How to Find a File in Directory in Java
September 30, 2022 - Recursion is an old-fashioned way to iterate over all the files and sub-directories and apply custom logic for matching the file names. Still, we can use it if it fits our solution. The following method findFilesByName() recursively iterates over the files and subdirectories and add the matching files into the foundFilesList.
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2017 โ€บ 01 โ€บ java-find-files-with-given-extension
Java โ€“ Find files with given extension
.png, .jpeg, .xml etc private static final String searchThisExtn = ".png"; public static void main(String args[]) { FindFilesWithThisExtn obj = new FindFilesWithThisExtn(); obj.listFiles(fileLocation, searchThisExtn); } public void listFiles(String loc, String extn) { SearchFiles files = new SearchFiles(extn); File folder = new File(loc); if(folder.isDirectory()==false){ System.out.println("Folder does not exists: " + fileLocation); return; } String[] list = folder.list(files); if (list.length == 0) { System.out.println("There are no files with " + extn + " Extension"); return; } for (String f
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ find files by extension in specified directory in java
Find Files by Extension in Specified Directory in Java | Baeldung
January 10, 2024 - Our first example will use a method thatโ€™s been around since the dawn of Java: Files.listFiles(). Letโ€™s start by instantiating a List to store our results and listing all files in the directory: List<File> find(File startPath, String extension) ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-search-for-a-file-in-a-directory
Java Program to Search for a File in a Directory - GeeksforGeeks
October 21, 2020 - Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is ...
๐ŸŒ
Crunchify
crunchify.com โ€บ java j2ee tutorials โ€บ in java how to perform file search operation using java.nio.file interface? tutorial on file and directory operations
In Java How to Perform File Search Operation using java.nio.file interface? Tutorial on File and Directory Operations โ€ข Crunchify
June 26, 2021 - In Java How to get list of files and search files from given folder? java.io.FilenameFilter Interface Example ยท If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. All in one Java Regex, Matcher Pattern and Regular Expressions Tutorial
๐ŸŒ
YouTube
youtube.com โ€บ watch
Finding Files and Directories Recursively with Java - YouTube
In this video, I am creating a small program that finds files and directories recursively. I hope you enjoyed this video if you did place leave a like and fe...
Published ย  April 8, 2021
๐ŸŒ
Javastudyguide
ocpj8.javastudyguide.com โ€บ ch25.html
Java 8 Programmer II Study Guide: Exam 1Z0-809
java.nio.file.Files, a class with static methods that we reviewed in the last chapter, added operations that return implementations of the Stream interface. ... static Stream<Path> find(Path start, int maxDepth, BiPredicate<Path, BasicFileAttributes> matcher, FileVisitOption...
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ list files in a directory in java
List Files in a Directory in Java | Baeldung
January 8, 2024 - Another disadvantage of using listFiles() is that it reads the whole directory at once. Consequently, it can be problematic for folders with a large number of files. So letโ€™s discuss an alternate way. Java 7 introduced an alternative to listFiles called DirectoryStream.