How to check a file if exists with wildcard in Java?

Pass a FileFilter (coded here anonymously) into the listFiles() method of the dir File, like this:

File dir = new File("some/path/to/dir");
final String id = "XXX"; // needs to be final so the anonymous class can use it
File[] matchingFiles = dir.listFiles(new FileFilter() {
    public boolean accept(File pathname) {
        return pathname.getName().equals("a_id_" + id + ".zip");
    }
});

Bundled as a method, it would look like:

public static File[] findFilesForId(File dir, final String id) {
    return dir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.getName().equals("a_id_" + id + ".zip");
        }
    });
}

and which you could call like:

File[] matchingFiles = findFilesForId(new File("some/path/to/dir"), "XXX");

or to simply check for existence,

boolean exists = findFilesForId(new File("some/path/to/dir"), "XXX").length > 0

Leave a Comment