Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
DrXCheng Avatar asked Jan 06 '12 00:01

DrXCheng


5 Answers

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

like image 153
Dave Hartnoll Avatar answered Oct 16 '22 15:10

Dave Hartnoll


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
like image 40
Bohemian Avatar answered Oct 16 '22 17:10

Bohemian


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));
    }
}
like image 23
Yeison Avatar answered Oct 16 '22 16:10

Yeison


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);
                }
            }
        }
    }
    
like image 6
GiantRobot Avatar answered Oct 16 '22 15:10

GiantRobot


You can use apache WildCardFileFilter

https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/filefilter/WildcardFileFilter.html

like image 1
nkare Avatar answered Oct 16 '22 17:10

nkare