gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:07:49 27 4
gpt4 key购买 nike

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

   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,我的模式是 .test(.)?.csv。我想存储与该通配符匹配的文件并将其存储在文件列表中。

最佳答案

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

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

关于java - 使用通配符过滤文件 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12743804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com