Java NIO Search file in a directory

java 8 find files matching pattern
java find file with partial name
java find file in directory and subdirectories
java find directory
java find files matching pattern recursively
java find file path
java find file in directory recursively
java program to search a file in computer

I want to search a file(without knowing the full name) in a specific directory using Java NIO and glob.

public static void match(String glob, String location) throws IOException {

        final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(
                glob);

        Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path,
                    BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(path)) {
                    System.out.println(path);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }

Reading some tutorial I did this. I just want to return string if I find(first) file with given glob String.

if (pathMatcher.matches(path)) {
    return path.toString();
}

There are two things to be changed:

To "find(first) file with given glob String" you need to finish walking the tree if you encounter the file, thus if a match is given. And you need to store the matching path as result. The result of Files.walkFileTree itself is the "the starting file" (JavaDoc). That's a Path pointing to the location.

public static String match(String glob, String location) throws IOException {
    StringBuilder result = new StringBuilder();
    PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
    Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
            if (pathMatcher.matches(path)) {
                result.append(path.toString());
                return FileVisitResult.TERMINATE;
            }
            return FileVisitResult.CONTINUE;
        }
    });

    return result.toString();
}

If there is no match then the resulting String is empty.

EDIT: Using Files.walk we can implement the search with less code still using a glob expression based matcher:

public static Optional<Path> match(String glob, String location) throws IOException {
    PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
    return Files.walk(Paths.get(location)).filter(pathMatcher::matches).findFirst();
}

The Optional as result shows that there may be no match.

Search File using NIO, In this Java NIO tutorial let us learn about putting FileVisitor and glob we can walk through the file system and search for a file or directory. In this tutorial we will go over java.nio.file.Path interface. Path is an object that may be used to locate a file in a file system. It will typically represent a system dependent file path. Some time back we have written an article on Java NIO (Non-blocking I/O) and we received so many feedback from users providing more and more tutorials on

Based on your own code. Just stop traversing once found some match

public class Main {

    private static Path found = "nothing"; // First file found

    public static void main(String[] args) throws IOException {
        String glob = "glob:**.{java}"; //pattern to look for
        String location = "D:\\"; //where to search
        match(location, glob);
        System.out.println("Found: " + found);
    }

    public static void match(String location, String glob) throws IOException {

        final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);

        Files.walkFileTree(Paths.get(location), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(path)) {
                    found = path; // Match found, stop traversal
                    return FileVisitResult.TERMINATE;
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

Or you can populate collection saving all the files matching the pattern

Finding Files (The Java™ Tutorials > Essential Classes > Basic I/O), For example, the following command lists all the files in the current directory that end The java.nio.file package provides programmatic support for this useful feature. Searching for files that match a particular pattern goes hand-in-hand with  In this example we are going to learn to use the DirectoryStream, which part of java.nio.file package, to find files in a directory. We are begin by creating a Path, the directory where the search will be conducted. After that we create a DirectoryStream using Files.newDirectoryStream(). To create a directory stream we passed two arguments, the starting path and a glob expression.

I don't know if this example could help you further, but it seems like you would need your own custom file visitor. Here is an alternative solution:

package com.jesperancinha.files;

import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class GlobFileVisitor extends SimpleFileVisitor<Path> {
    private final PathMatcher pathMatcher;

    private Path path;

    public GlobFileVisitor(String glob) {
        this.pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
    }

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
        if (pathMatcher.matches(path)) {
            this.path = path;
            return FileVisitResult.TERMINATE;
        }
        return FileVisitResult.CONTINUE;
    }

    public Path getFoundPath() {
        return path;
    }
}

And this is another possibility for your running example:

package com.jesperancinha.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileFinder {
    public static void main(String[] args) throws IOException {
        String glob = "glob:**.{java}";
        String location = "/Users/joao/dev/src/jesperancinha";
        Path found = match(location, glob);
        System.out.println("Found: " + found);
    }

    public static Path match(String location, String glob) throws IOException {
        GlobFileVisitor globFileVisitor = new GlobFileVisitor(glob);
        Files.walkFileTree(Paths.get(location), globFileVisitor);
        return globFileVisitor.getFoundPath();
    }
}

In Java How to Perform File Search Operation using java.nio.file , Search Operation using java.nio.file interface? Tutorial on File and Directory Operations. Last Updated on December 1st, 2019 by App Shah Leave a comment. How to search for a file in a directory ? Solution. Following example shows how to search for a particular file in a directory by making a Filefiter. Following example displays all the files having file names starting with 'b'.

How do I find files in a directory using DirectoryStream?, nio.file package, to find files in a directory. We are begin by creating a Path , the directory where the search will be conducted. The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher. You can retrieve a file system's PathMatcher by using the getPathMatcher (String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:

List Files in a Directory in Java, 4. Walking. Or, we can list all the files within a directory by walking it to a configured depth. Let's use java.nio.file.Files#walk to list all the files  Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing the DirectoryStream.Filter<T> interface. This interface consists of one method, accept, which determines whether a file fulfills the search requirement.

Java IO & NIO - Files.find() Examples, Parameters: start - the starting file: maxDepth - the maximum number of directory levels to search: matcher - the function used to decide whether  Two Java examples to show you how to list files in a directory : For Java 8, Files.walk Before Java 8, create a recursive loop to list all files. 1. Files.walk

Comments
  • Use a nullable String instead of a StringBuilder. That's less overhead and still accurte
  • How should this work? The String variable wouldn't be effective final anymore.
  • You're right. Maybe put an AtomicReference or use a var wrapper = new Object() { Path reference; } if you use Java 11+.
  • Do you think this would be more readable? Is this because you prefer return null instead of an empty String if no result is found?
  • Or try(Stream<Path> stream = Files.find​(Paths.get(location), Integer.MAX_VALUE, (path,attr) -> pathMatcher.matches​(path))) { return stream.findFirst().orElse(null); }
  • I'm not sure what you expect {prop*} to do but I'd avoid mixing the {alt1,alt2,...} syntax with wildcards. I just tested it under bash and the inner wildcard isn't expanded but rather understood as a literal *. I haven't tested with Java so it might just work, but you'd be at least sure to confuse people familiar with linux
  • @Aaron used it to look for properties in Windows. Not sure about bash but you are right, better to edit to avoid potential troubles
  • Also, the OP wants to return a string. Could you put the found in the match method and return it at the end of the method, making the void-returning method a Path-returning method?