Languages
[Edit]
EN

Java - find file by filename inside directory

0 points
Created by:
Lennie-S
289

In this article, we would like to show you how to find a file by filename in the specified directory in Java.

Project structure

/C/
 └── directory/
      ├── subdirectory1/
      │           └── file.txt
      └── subdirectory2/

Practical examples

In this example, we use Files.find() method to search for file.txt starting from C:/directory folder.

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Collectors;


public class Example {

    public static void main(String[] args) throws IOException {
        Path directoryPath = Paths.get("C:\\directory");
        String filename = "file.txt";
        List<Path> result;

        try (Stream<Path> pathStream = Files.find(directoryPath,
                Integer.MAX_VALUE,
                (path, basicFileAttributes) ->
                        path.getFileName().toString().equalsIgnoreCase(filename))
        ) {
            result = pathStream.collect(Collectors.toList());
        }
        result.forEach(System.out::println);
    }
}

Output:

C:\directory\subdirectory1\file.txt

Java - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join