如果类路径中有两个 JAR 文件,它们的根目录中都包含名为“config.properties”的资源。有没有办法找回both文件类似于getClass().getResourceAsStream()
?该顺序不相关。
另一种方法是加载类路径中符合特定条件的每个属性文件(如果可能的话)。
你需要ClassLoader.getResources(name) http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResources%28java.lang.String%29
(或静态版本ClassLoader.getSystemResources(name) http://download.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemResources%28java.lang.String%29).
但不幸的是,不在“目录”内的资源存在一个已知问题。例如。foo/bar.txt
很好,但是bar.txt
可能是个问题。这是Spring Reference 中描述得很好 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/resources.html#resources-wildcards-in-path-other-stuff,尽管这绝不是 Spring 特有的问题。
Update:
这是一个返回输入流列表的辅助方法:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)