5

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();
}
0

4 Answers 4

7

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.

5
  • Use a nullable String instead of a StringBuilder. That's less overhead and still accurte Dec 11, 2018 at 9:28
  • How should this work? The String variable wouldn't be effective final anymore.
    – LuCio
    Dec 11, 2018 at 9:30
  • You're right. Maybe put an AtomicReference or use a var wrapper = new Object() { Path reference; } if you use Java 11+. Dec 11, 2018 at 9:34
  • 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?
    – LuCio
    Dec 11, 2018 at 9:36
  • Or try(Stream<Path> stream = Files.find​(Paths.get(location), Integer.MAX_VALUE, (path,attr) -> pathMatcher.matches​(path))) { return stream.findFirst().orElse(null); }
    – Holger
    Dec 21, 2018 at 16:14
4

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

3
  • 1
    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
    Dec 11, 2018 at 9:13
  • @Aaron used it to look for properties in Windows. Not sure about bash but you are right, better to edit to avoid potential troubles
    – Akceptor
    Dec 11, 2018 at 9:15
  • 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? Dec 11, 2018 at 9:17
1

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();
    }
}
0
0

These answers will all work, but the intended way to search for files with NIO is Files.Find with a BiPreicate<Path,BasicFileAttributes>.

PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.txt");
Stream<Path> stream = Files.find(
        Paths.get("/dirToSearch"),
        1, // Search depth of 1 in our case, set to >1 or -1 to explore subfolders
        (path, basicFileAttributes) ->  matcher.matches(path)
);
// The stream is lazily populated
Path firstMatch = stream.findFirst().get();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.