用于搜索目录的 Java 通配符

时间:2021-06-01 07:13:37

标签: java path wildcard

我需要搜索一个会因不同环境而改变的文件夹。虽然文件名保持不变,但文件夹名称已更改。

在下面的截图中,分支名称随着环境的变化而变化;配置和日志文件保持不变。

enter image description here

我想使用通配符搜索分支名称文件夹中的配置。我使用了以下内容,但这似乎不起作用并返回一条错误消息,指出未找到路径。

String LOCAL_DIR = "*/config/";

应该怎么做才能搜索 branch-name 文件夹而不传递它,因为名称在各种环境中都发生了变化?

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您可以使用库,我们可以在您可以提及的根文件夹中进行递归搜索,并通过搜索以 .log 作为扩展名的文件来实现这一点

马文:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.9.0</version>
</dependency>

示例代码:

import java.io.File;
import java.util.Collection;

import org.apache.commons.io.FileUtils;

public class Test {

    public static void main(String[] args) {
        
        //mention the file suffix
        String[] SUFFIX = {"log"};
        
        //mention your root directory here to do a recursive search
        String root_dir = "C:\\work";
        
        Collection<File> files = FileUtils.listFiles(new File(root_dir), SUFFIX, true);
        
        for(File file: files) {
            if(file.getAbsolutePath().contains("/config/") //this will be good for unix/linux
                        || file.getAbsolutePath().contains("\\config\\") //this will be good for windows
                    ) {
                //this is your required file meeting all the criteria
                System.out.println(file.getAbsolutePath());
            }
        }
        
    }

}
相关问题