How to find file in directory

In this tutorial we will find out how to find file (by its name) inside the specified directory using different methods and libraries.

Java 6

Finding the file inside directory recursively (including subdirectories), the logic of traversing through the directory structure is written manually:

public File findFilesInFolderRecursively(File checkedFile, String searchedFilename) {
    if (checkedFile.getName().equals(searchedFilename)) {
        return checkedFile;
    }
    if (checkedFile.isDirectory()) {
        for (File file : checkedFile.listFiles()) {
            File foundFile = findFilesInFolderRecursively(file, searchedFilename);
            if (foundFile != null) {
                return foundFile;
            }
        }
    }
    return null;
}

Apache Commons

Using the Apache Commons FileUtils.listFiles method, that returns collection of found files:

public File findFilesInFolderUsingApacheCommonsIO(File checkedFile, String searchedFilename) {
    IOFileFilter fileFilter = new NameFileFilter(searchedFilename);
    IOFileFilter dirFilter = FileFilterUtils.trueFileFilter() ;
    Collection<File> files = FileUtils.listFiles(checkedFile, fileFilter, dirFilter);
    if (files.size() > 0) {
        return files.iterator().next();
    }
    return null;
}

Google Guava

Using the Google Guava Files.fileTreeTraverser method to iterate over the files in the directory. Note that in never versions of the library the method changed its name to Files.fileTraverser.

public File findFilesInFolderUsingGuava(File checkedFile, String searchedFilename) {
    for (File file : Files.fileTreeTraverser().breadthFirstTraversal(checkedFile)) {
        if (file.getName().equals(searchedFilename)) {
            return file;
        }
    }
    return null;
}

Java 8

Java 8 provides NIO (New IO) Api with Files.find method:

public Optional<Path> findFilesInFolderJava8(String checkedDirectory, String searchedFilename) throws IOException {
    return Files.find(Paths.get(checkedDirectory), 100, (path, basicFileAttributes) -> {
        File file = path.toFile();
        return file.getName().equals(searchedFilename);
    }).findFirst();
}

Finding a file in directory using NIO Files.walk method:

public Optional<Path> findFilesInFolderJava8(String checkedDirectory, String searchedFilename) throws IOException {
return Files.walk(Paths.get(checkedDirectory), 100)
.filter(path -> path.getFileName().toFile().getName().equals(searchedFilename))
.findFirst();
}