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

i created zip files named with a_id_123.zip ,a_id_124.zip ,a_id_125.zip ,a_id_126.zip and it looks like working fine but i'm not sure if it's proper answer for you. Output will be the following if files listed above exists

  • found a_id_123.zip
  • found a_id_124.zip
  • found a_id_125.zip
  • found a_id_126.zip

    public static void main(String[] args) {
    
        String pathToScan = ".";
        String fileThatYouWantToFilter;
        File folderToScan = new File(pathToScan); // import -> import java.io.File;
        File[] listOfFiles = folderToScan.listFiles();
    
        for (int i = 0; i < listOfFiles.length; i++) {
    
            if (listOfFiles[i].isFile()) {
                fileThatYouWantToFilter = listOfFiles[i].getName();
                if (fileThatYouWantToFilter.startsWith("a_id_")
                        && fileThatYouWantToFilter.endsWith(".zip")) {
                    System.out.println("found" + " " + fileThatYouWantToFilter);
                }
            }
        }
    }
    

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