使用通配符过滤文件(java)

时间:2012-10-05 09:54:12

标签: java file wildcard

使用通配符我想处理目录中的文件。如果指定了通配符,我想处理那些与通配符char匹配的文件,如果没有指定,我将处理所有文件。这是我的代码

   List<File> fileList;
   File folder = new File("Directory");
   File[] listOfFiles = folder.listFiles();
    if(prop.WILD_CARD!=null) {  
        Pattern wildCardPattern = Pattern.compile(".*"+prop.WILD_CARD+"(.*)?.csv",Pattern.CASE_INSENSITIVE);
        for(File file: listOfFiles) {
            Matcher match = wildCardPattern.matcher(file.getName());
            while(match.find()){
                String fileMatch = match.group();
                if(file.getName().equals(fileMatch))  {
                    fileList.add(file); // doesn't work
                }
            }
        }
    }
    else
        fileList = new LinkedList<File>( Arrays.asList(folder.listFiles()));

我无法将匹配通配符的文件放在单独的文件列表中。请帮我修改我的代码,以便我可以将所有匹配通配符的文件放在一个单独的文件列表中。在这里我在我的正则表达式中连接prop.WILD_CARD,它可以是任何字符串,例如,如果外卡是测试,我的模式是。 test(。)?。csv。我想存储与此通配符匹配的文件并将其存储在文件列表中。

2 个答案:

答案 0 :(得分:1)

我刚测试了这段代码,运行得很好。您应该检查其他地方的逻辑错误。

    public static void main(String[] args) {

    String WILD_CARD = "";
     List<File> fileList = new LinkedList<File>();
       File folder = new File("d:\\");
       File[] listOfFiles = folder.listFiles();
        if(WILD_CARD!=null) {  
            Pattern wildCardPattern = Pattern.compile(".*"+WILD_CARD+"(.*)?.mpp",Pattern.CASE_INSENSITIVE);
            for(File file: listOfFiles) {
                Matcher match = wildCardPattern.matcher(file.getName());
                while(match.find()){
                    String fileMatch = match.group();
                    if(file.getName().equals(fileMatch))  {
                        fileList.add(file); // doesn't work
                    }
                }
            }
        }
        else
            fileList = new LinkedList<File>( Arrays.asList(folder.listFiles()));

        for (File f: fileList) System.out.println(f.getName());
}

这将返回D:驱动器上所有* .mpp文件的列表。

我还建议使用

        for (File file : listOfFiles) {
            Matcher match = wildCardPattern.matcher(file.getName());
            if (match.matches()) {
                fileList.add(file);
            }
        }

答案 1 :(得分:0)

我建议您查看FilenameFilter类,看看它是否有助于简化代码。至于你的正则表达式,我认为你需要逃避“。”它的特点是工作。