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

前端 未结 16 944
慢半拍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:03

    You could convert your wildcard string to a regular expression and use that with String's matches method. Following your example:

    String original = "../Test?/sample*.txt";
    String regex = original.replace("?", ".?").replace("*", ".*?");
    

    This works for your examples:

    Assert.assertTrue("../Test1/sample22b.txt".matches(regex));
    Assert.assertTrue("../Test4/sample-spiffy.txt".matches(regex));
    

    And counter-examples:

    Assert.assertTrue(!"../Test3/sample2.blah".matches(regex));
    Assert.assertTrue(!"../Test44/sample2.txt".matches(regex));
    
    0 讨论(0)
  • 2020-11-22 11:11

    Might not help you right now, but JDK 7 is intended to have glob and regex file name matching as part of "More NIO Features".

    0 讨论(0)
  • 2020-11-22 11:11

    Why not use do something like:

    File myRelativeDir = new File("../../foo");
    String fullPath = myRelativeDir.getCanonicalPath();
    Sting wildCard = fullPath + File.separator + "*.txt";
    
    // now you have a fully qualified path
    

    Then you won't have to worry about relative paths and can do your wildcarding as needed.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 11:13
    Path testPath = Paths.get("C:\");
    
    Stream<Path> stream =
                    Files.find(testPath, 1,
                            (path, basicFileAttributes) -> {
                                File file = path.toFile();
                                return file.getName().endsWith(".java");
                            });
    
    // Print all files found
    stream.forEach(System.out::println);
    
    0 讨论(0)
  • 2020-11-22 11:14

    Simple Way without using any external import is to use this method

    I created csv files named with billing_201208.csv ,billing_201209.csv ,billing_201210.csv and it looks like working fine.

    Output will be the following if files listed above exists

    found billing_201208.csv
    found billing_201209.csv
    found billing_201210.csv
    

        //Use Import ->import java.io.File
            public static void main(String[] args) {
            String pathToScan = ".";
            String target_file ;  // fileThatYouWantToFilter
            File folderToScan = new File(pathToScan); 

        File[] listOfFiles = folderToScan.listFiles();
    
         for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    target_file = listOfFiles[i].getName();
                    if (target_file.startsWith("billing")
                         && target_file.endsWith(".csv")) {
                    //You can add these files to fileList by using "list.add" here
                         System.out.println("found" + " " + target_file); 
                    }
               }
         }    
    }
    

    0 讨论(0)
提交回复
热议问题