我有一个带有多个模块的Java应用程序,每个模块都有一个jar
文件。每个jar文件都遵循相同的名为META-INF/props
的文件夹结构。在java中有没有一种方法可以使用通配符加载多个jar的`META-INF/props中的所有属性文件?
类似的东西
ClassLoader.getSystemResourceAsStream("META-INF/props/*.properties");
我知道这种方法不接受通配符,也不返回流数组,但有可能这样做吗?
不,没有标准/可靠的方法可以做到这一点。一些库利用ClassLoader.getResources实现的常见模式(特别是,它们通常总是返回"file:"或"jar:file:"URL),以便在资源查找中支持通配符。例如,应用程序上下文构造函数资源路径中的通配符解释了Spring是如何做到这一点的,它列出了几个注意事项("对可移植性的影响"、"Classpath*:可移植性"、"与通配符相关的注意事项")。
我写了一些代码来绕过这个限制。
我读取类路径中的所有条目,确定它是文件夹还是JAR文件,然后在"META_INF/props"中查找条目。如果条目是属性,我会加载它。
下面是代码,它没有经过提炼,但给出了大致的想法。
try{
URL[] urls = ((URLClassLoader) LoaderTest.class.getClassLoader()).getURLs();
HashMap<String, Properties> mapProperties = new HashMap<String, Properties>();
for(URL url: urls){
File file = new File(url.getFile());
if(file.isDirectory()){
System.out.println("Directory: " +file.getName());
File propFolder = new File(file.getAbsolutePath() + "/META-INF/props");
if (propFolder.exists() && propFolder.isDirectory()){
for(File f: propFolder.listFiles()){
if(f.getName().endsWith("properties") || f.getName().endsWith("props")){
Properties props = new Properties();
props.load(new FileReader(f));
String appName = props.getProperty("load.global.props.appName");
if(appName != null){
if( mapProperties.get(appName) == null) {
mapProperties.put(appName, props);
} else {
mapProperties.get(appName).putAll(props);
}
}
}
}
}
} else if (file.getName().endsWith("jar")){
System.out.println("Jar File: " + file.getName());
JarFile jarFile = null;
try{
jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while ( entries.hasMoreElements() ){
JarEntry entry = entries.nextElement();
if ( entry.getName().startsWith("META-INF/props") &&
(entry.getName().endsWith("properties") ||
entry.getName().endsWith("props"))){
System.out.println("Prop File: " + entry.getName());
Properties props = new Properties();
props.load(jarFile.getInputStream(entry));
String appName = props.getProperty("load.global.props.appName");
if(appName != null){
if( mapProperties.get(appName) == null) {
mapProperties.put(appName, props);
} else {
mapProperties.get(appName).putAll(props);
}
}
}
}
} finally {
if ( jarFile != null ) jarFile.close();
}
}
}
} catch(Exception e){
e.printStackTrace();
}