How to find files that match a wildcard string in Java?

前端 未结 16 1130
慢半拍i
慢半拍i 2020-11-22 10:52

This should be really simple. If I have a String like this:

../Test?/sample*.txt

then what is a generally-accepted way to get a list of fil

16条回答
  •  遥遥无期
    2020-11-22 11:11

    Util Method:

    public static boolean isFileMatchTargetFilePattern(final File f, final String targetPattern) {
            String regex = targetPattern.replace(".", "\\.");  //escape the dot first
            regex = regex.replace("?", ".?").replace("*", ".*");
            return f.getName().matches(regex);
    
        }
    

    jUnit Test:

    @Test
    public void testIsFileMatchTargetFilePattern()  {
        String dir = "D:\\repository\\org\my\\modules\\mobile\\mobile-web\\b1605.0.1";
        String[] regexPatterns = new String[] {"_*.repositories", "*.pom", "*-b1605.0.1*","*-b1605.0.1", "mobile*"};
        File fDir = new File(dir);
        File[] files = fDir.listFiles();
    
        for (String regexPattern : regexPatterns) {
            System.out.println("match pattern [" + regexPattern + "]:");
            for (File file : files) {
                System.out.println("\t" + file.getName() + " matches:" + FileUtils.isFileMatchTargetFilePattern(file, regexPattern));
            }
        }
    }
    

    Output:

    match pattern [_*.repositories]:
        mobile-web-b1605.0.1.pom matches:false
        mobile-web-b1605.0.1.war matches:false
        _remote.repositories matches:true
    match pattern [*.pom]:
        mobile-web-b1605.0.1.pom matches:true
        mobile-web-b1605.0.1.war matches:false
        _remote.repositories matches:false
    match pattern [*-b1605.0.1*]:
        mobile-web-b1605.0.1.pom matches:true
        mobile-web-b1605.0.1.war matches:true
        _remote.repositories matches:false
    match pattern [*-b1605.0.1]:
        mobile-web-b1605.0.1.pom matches:false
        mobile-web-b1605.0.1.war matches:false
        _remote.repositories matches:false
    match pattern [mobile*]:
        mobile-web-b1605.0.1.pom matches:true
        mobile-web-b1605.0.1.war matches:true
        _remote.repositories matches:false
    

提交回复
热议问题