简体   繁体   中英

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

I have a directory, and inside it are files are named "a_id_XXX.zip" .

How do check if a file exists given an id and File dir ?

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

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

This solution generalizes on Bohemian's answer. It uses regular expressions and also replaces the inner class with Java 8 lambda expressions. Thanks @Bohemian for the original implementation.

import java.io.File;

public class FileFinder {
    public static void main(String[] args){
        File directory = new File("D:\\tmp");
        String id = "20140430104033";
        for (File f : findFilenamesWithId(id, directory)){
            System.out.println(f.getAbsoluteFile());
        }
    }

    /** Finds files in the specified directory whose names are formatted 
        as "a_id_ID.zip" */
    public static File[] findFilenamesWithId(String ID, File dir) {
        return findFilenamesMatchingRegex("^a_id_" + ID + "\\.zip$", dir);
    }

    /** Finds files in the specified directory whose names match regex */
    public static File[] findFilenamesMatchingRegex(String regex, File dir) {
        return dir.listFiles(file -> file.getName().matches(regex));
    }
}

Java 7 has some good support for pattern matching (PathMatcher) and recursive directory walking (Files.walkFileTree()). In the context of the original question, this page in Oracle's Java documentation is a good start:

Finding Files: http://docs.oracle.com/javase/tutorial/essential/io/find.html

Using Java 8 find all files in directory and sub directory with required regex condition

My condition is to find all files with Audit_Report_xxxxxx.xls

// get List of Audit Report file in directory and sub directory
public List<String> getAuditReporFile(String baseDirectory) throws Exception{

    // select all available files in directory and subdirectory
    return Files.walk(Paths.get(baseDirectory))
            .filter(Files::isRegularFile).filter(x-> {

                // use regex and check if file name is according to our requirement
                return Pattern.compile("Audit_Report_.*\\.xls").matcher(x.getFileName().toString()).find();

            }).map(x->x.getFileName().toString()).collect(Collectors.toList());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM