Path.getFilename() does not return a String, but a Path object, do this:

getFilename().toString().equals("workspace")
Answer from David 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)
The PathMatcher interface has a single method, matches, that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:
🌐
Stack Overflow
stackoverflow.com › questions › 61186537 › what-is-the-best-way-to-find-files-using-java-8
What is the best way to find files using Java 8? - Stack Overflow
0 Finding a specific file in a folder in java · 2 Locating a file with Java · 0 Find specific file · 4 How to search a file? 1 (Java) Searching Computer For a Specific File (a faster way) 8 How to use Java 8 `Files.find` method? Slow rise time for a temperature sensor ·
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › listing all files in a directory in java
Listing All Files in a Directory in Java
October 1, 2022 - To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples. List<File> files = Files.list(Paths.get(dirLocation)) .filter(path -> path.toFile().isHidden()) .map(Path::toFile) .collect(Collectors.toList()); In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods.
Find elsewhere
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

🌐
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 - There are total 10 files. /Users/appshah/Desktop/screenshots/c.png /Users/appshah/Desktop/screenshots/ct.png /Users/appshah/Desktop/screenshots/Good to see Crunchify article featured on Google SERP.png /Users/appshah/Desktop/screenshots/In Java How to Perform File Search Operation using java.nio.file interface?.png /Users/appshah/Desktop/screenshots/java.nio.file.Path interface in Java8.png /Users/appshah/Desktop/screenshots/Screen Shot 2016-06-29 at 12.58.08 PM.png /Users/appshah/Desktop/screenshots/Screen Shot 2016-08-01 at 12.16.05 PM.png /Users/appshah/Desktop/screenshots/Screen Shot 2016-08-17 at 5.57.41 PM.png /Users/appshah/Desktop/screenshots/Screen Shot 2016-11-08 at 9.25.52 PM.png /Users/appshah/Desktop/screenshots/Screen Shot 2016-11-09 at 2.06.57 PM.png You have total 10 .png files under directory /Users/appshah/Desktop/screenshots
🌐
Winterbe
winterbe.com › posts › 2015 › 03 › 25 › java8-examples-string-number-math-files
Java 8 API by Example: Strings, Numbers, Math and Files - winterbe
The method find accepts three arguments: The directory path start is the initial starting point and maxDepth defines the maximum folder depth to be searched. The third argument is a matching predicate and defines the search logic. In the above example we search for all JavaScript files (filename ends with .js).
🌐
Javastudyguide
ocpj8.javastudyguide.com › ch25.html
Java 8 Programmer II Study Guide: Exam 1Z0-809
As you can see, this method lists directories and files in the specified directory.
🌐
Mkyong
mkyong.com › home › java › java files.walk examples
Java Files.walk examples - Mkyong.com
December 2, 2020 - package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; // Files.walk example public class FilesWalkExample6 { public static void main(String[] args) throws IOException { Path path = Paths.get("C:\\test\\"); long fileSizeInBytes = 1024 * 1024 * 10; // 10MB List<Path> paths = findByFileSize(path, fileSizeInBytes); paths.forEach(x -> System.out.println(x)); } // fileSize in bytes public static List<Path> findByFileSize(Path p
Top answer
1 of 2
4

Yes you can do it. Assuming you have paths as a List of String objects, you can do it like so,

List<String> paths = ...;

paths.stream().map(path -> {
    try (Stream<Path> stream = Files.list(Paths.get(path))) {
        return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
                .map(Path::toString).collect(Collectors.joining("\n"));
    } catch (IOException e) {
        // Log your ERROR here.
        e.printStackTrace();
    }
    return "";
}).forEach(System.out::println);

In case if you need to get rid of the new-line character, then it can be done like this too.

paths.stream().map(path -> {
    try (Stream<Path> stream = Files.walk(Paths.get(path))) {
        return stream.filter(p -> !p.toFile().isDirectory()).filter(p -> p.toString().endsWith(".json"))
                .map(Path::toString).collect(Collectors.toList());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Collections.emptyList();
}).flatMap(List::stream).forEach(System.out::println);

Here you get all the .json file names for each path into a List, and then flatten them into a flat stream of String objects before printing. Notice that the additional step involved in this approach which is flatMap.

2 of 2
3

That’s what flatMap is for.

If you have a collection of Path instances in path, you may use

paths.stream()
     .flatMap(path -> {
         try { return Files.find(path, Integer.MAX_VALUE,
            (p, attrs) -> attrs.isRegularFile() && p.toString().endsWith(".json")); }
         catch (IOException ex) { throw new UncheckedIOException(ex); }
     })
     .forEach(System.out::println);

It is a bit clumsy due to the fact that we have to deal with the checked IOException declared by find here. Rethrowing it as UncheckedIOException is the simplest choice as that’s what the stream returned by find will do anyway if an I/O problem occurs while processing the stream. Compare with the documentation of find

If an IOException is thrown when accessing the directory after returned from this method, it is wrapped in an UncheckedIOException which will be thrown from the method that caused the access to take place.

So doing the same within our function simplifies the caller’s error handling, as it just has to handle UncheckedIOExceptions.

There is no way to use try(…) here, but that’s exactly the reason why flatMap will remove this burden from us. As its documentation states:

Each mapped stream is closed after its contents have been placed into this stream.

So, once our function has returned the sub-stream, the Stream mplementation will do the right thing for us.

You may chain arbitrary stream operations in place of .forEach(System.out::println); to process all elements of the flattened stream like a single stream.

If your input collection contains instances of String instead of Path, you may simply prepend paths.stream().map(Paths::get) instead of paths.stream() to the flatMap operation.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - The elements returned by the directory stream's iterator are of type Path, each one representing an entry in the directory. The Path objects are obtained as if by resolving the name of the directory entry against dir. The entries returned by the iterator are filtered by matching the String representation of their file names against the given globbing pattern. For example, suppose we want to iterate over the files ending with ".java" in a directory:
🌐
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 - First, we used listFiles() to get all the contents of the folder. Then we used DirectoryStream to lazy load the directory’s content. We also used the list() method introduced with Java 8.
🌐
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 - The following method findFilesByName() recursively iterates over the files and subdirectories and add the matching files into the foundFilesList.
🌐
Niraj Sonawane
nirajsonawane.github.io › 2018 › 05 › 23 › java-8-List-All-Files-in-Directory
Java 8 List All Files in Directory | Niraj Sonawane
May 24, 2018 - Files.list Method Return a lazily populated Stream, the elements of which are the entries in the directory. We Can use the stream operations to find Specific Files, List file matching certain criteria, List filenames in sorted order etc.