java 如何从不同的 JAR 中读取多个同名的资源文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6730580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:02:58  来源:igfitidea点击:

How to read several resource files with the same name from different JARs?

javaclasspath

提问by Zeemee

If there are two JAR files in the classpath, both containing a resource named "config.properties" in its root. Is there a way to retrieve bothfiles similar to getClass().getResourceAsStream()? The order is not relevant.

如果类路径中有两个 JAR 文件,它们的根目录中都包含一个名为“config.properties”的资源。有没有办法检索类似于 的两个文件getClass().getResourceAsStream()?订单不相关。

An alternative would be to load every property file in the class path that match certain criterias, if this is possible at all.

另一种方法是加载类路径中匹配特定条件的每个属性文件,如果这可能的话。

采纳答案by Sean Patrick Floyd

You need ClassLoader.getResources(name)
(or the static version ClassLoader.getSystemResources(name)).

您需要 (或静态版本)。ClassLoader.getResources(name)
ClassLoader.getSystemResources(name)

But unfortunately there's a known issue with resources that are not inside a "directory". E.g. foo/bar.txtis fine, but bar.txtcan be a problem. This is described well in the Spring Reference, although it is by no means a Spring-specific problem.

但不幸的是,不在“目录”内的资源存在一个已知问题。例如foo/bar.txt很好,但bar.txt可能是一个问题。这在 Spring Reference 中有很好的描述,尽管它绝不是 Spring 特定的问题。

Update:

更新:

Here's a helper method that returns a list of InputStreams:

这是一个返回 InputStreams 列表的辅助方法:

public static List<InputStream> loadResources(
        final String name, final ClassLoader classLoader) throws IOException {
    final List<InputStream> list = new ArrayList<InputStream>();
    final Enumeration<URL> systemResources = 
            (classLoader == null ? ClassLoader.getSystemClassLoader() : classLoader)
            .getResources(name);
    while (systemResources.hasMoreElements()) {
        list.add(systemResources.nextElement().openStream());
    }
    return list;
}

Usage:

用法:

List<InputStream> resources = loadResources("config.properties", classLoader);
// or:
List<InputStream> resources = loadResources("config.properties", null);

回答by mbarnes

jar files are zip files.

jar 文件是 zip 文件。

Open the file using java.util.zip.ZipFile

使用 java.util.zip.ZipFile 打开文件

Then enumerate its entries looking for the properties file you want.

然后枚举其条目以查找所需的属性文件。

When you have the entry you can get its stream with .getInputStream()

当您有条目时,您可以使用 .getInputStream() 获取其流