How to Find a File in Directory in Java

Learn different ways to find a file in a given directory and sub-directories with Java. The given examples will find all files with specified file names if there are more than one files with the same name in the sub-directories.

1. Find File by Walking the Directories

The easiest and most straightforward way of finding all files in a directory or its subdirectories is walking all the files using Files.walk() method. This method traverses the directories in a depth-first manner, so files in the deep-most sub-directories are searched first.

We can optionally pass the depth of the sub-directory level to search if the directory structure is too much nested and we do not wish to go that much deeper. Note that when we close the Stream, the directory is also closed.

String fileNameToFind = "test.txt";
File rootDirectory = new File("c:/temp");

final List<File> foundFiles = new ArrayList<>();

try (Stream<Path> walkStream = Files.walk(rootDirectory.toPath())) {
  walkStream.filter(p -> p.toFile().isFile())
      .forEach(f -> {
        if (f.toString().endsWith(fileNameToFind)) {
          foundFiles.add(f.toFile());
        }
      });
}

If we want to iterate over 5 levels of sub-directories then we can use the following function:

try (Stream<Path> walkStream = Files.walk(rootDirectory.toPath(), 5)) {
	...
}

If we want to stop the search after the first file is found then we can use the Stream.findFirst() method with the stream of paths.

Optional<Path> foundFile;

try (Stream<Path> walkStream = Files.walk(rootDirectory.toPath())) {
  foundFile = walkStream.filter(p -> p.toFile().isFile())
      .filter(p -> p.toString().endsWith(fileNameToFind))
      .findFirst();
}

if(foundFile.isPresent()) {
  System.out.println(foundFile.get());
} else {
  System.out.println("File not found");
}

2. Using Recursion

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.

The recursive function first lists all the files using File.listFiles() method and then iterates over them. During iteration, it further calls the listFiles() for all child directories that it checks using the file.isDirectory() method.

After the recursion ends, we can check the files found in this list.

final List<File> foundFilesList = new ArrayList<>();
findFilesByName(rootDirectory, fileNameToFind, foundFilesList);

public static void findFilesByName(File rootDir, String filenameToSearch, List<File> foundFilesList) {

  Collection<File> files = List.of(rootDir.listFiles());

  for (Iterator iterator = files.iterator(); iterator.hasNext(); ) {
    File file = (File) iterator.next();
    if (file.isDirectory()) {
      findFilesByName(file, filenameToSearch, foundFilesList);
    } else if(file.getName().equalsIgnoreCase(filenameToSearch)){
      foundFilesList.add(file);
    }
  }
}

System.out.println(foundFilesList); //Prints the found files

3. Conclusion

This short Java tutorial taught us to find a file by name in a given directory and its sub-directories. We also learned to control the search up to a configured depth of sub-directories. We used the Stream reduction method findFirst() as well if we wanted to terminate the search after the first occurrence of a matching file.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.