Search code examples
javafile-search

Search a file in a directory using wildcards


I need to check if some files exist in a directory using Java but the file name have a pattern. For example the file name is recap_data_03082017.txt and the numbers at the end are always changing. Is there a way to perform a search using a wildcard like recap_data_*.csv


Solution

  • If you are using Java 8, you could try the following,

     try (Stream<Path> paths = Files.walk(Paths.get("/your/path/"), 1)) {
                return paths
                        .filter(Files::isRegularFile)
                        .anyMatch(f -> {
                            final String fileName = f.getFileName().toString();
                            return fileName.startsWith("ecap_data_") && fileName.endsWith(".csv");
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }