Languages
[Edit]
EN

Java - find file by filename inside directory

0 points
Created by:
Lennie-S
439

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

Alternative titles

  1. Java - search for file in directory
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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