如何从不同的JAR中读取多个具有相同名称的资源文件? [英] How to read several resource files with the same name from different JARs?

查看:121
本文介绍了如何从不同的JAR中读取多个具有相同名称的资源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 both files similar to getClass().getResourceAsStream()? The order is not relevant.

另一种方法是在类路径中加载符合某些标准的每个属性文件(如果可能的话)。

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

推荐答案

你需要 ClassLoader.getResources(name)

(或静态版本 ClassLoader.getSystemResources(name) )。

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

但遗憾的是资源存在已知问题不在目录中。例如。 foo / bar.txt 没问题,但 bar.txt 可能有问题。这是在Spring Reference 中很好地描述了,虽然它绝不是Spring特有的问题。

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

更新:

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

Here's a helper method that returns a list of 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;
}

用法:

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

这篇关于如何从不同的JAR中读取多个具有相同名称的资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆