Is it possible load all properties files contained in a package dynamically? i.e. MyClass.class.getResource('*.properties');
I am familiar with obtaining the contents of a properties file given the name of the file, and obviously MyClass.class.getResource('*.properties') will not work, but how can I obtain a list of ALL the properties files located开发者_StackOverflow中文版 in the same package as my class?
Assuming that it's not JAR-packaged, you can use File#listFiles()
for this. Here's a kickoff example:
String path = MyClass.class.getResource("").getPath();
File[] propertiesFiles = new File(path).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".properties");
}
});
If it's JAR-packaged, then you need a bit more code, to start with JarFile
API. You can find another example in this answer.
You can do these sort of things with Spring. See 4. Resources, particurlarely (or notabily ? ) (or principalementely ? ) (or mainly ? ) at 4.7.2 Wildcards in application context constructor resource paths.
This is how I did it,
Class<? extends Object> clazz = AnyKnownClassInTheJar.class;
String classFileName = clazz.getSimpleName() + ".class";
URL classResource = clazz.getResource(classFileName);
if (!"jar".equals(classResource.getProtocol())) {
// Class not from JAR
return;
}
JarURLConnection classConnection = (JarURLConnection)classResource.openConnection();
JarFile jar = classConnection.getJarFile();
for (Enumeration<JarEntry> i = jar.entries(); i.hasMoreElements();) {
JarEntry entry = i.nextElement();
if (entry.getName().endsWith(".properties")) {
// Load the property file
}
}
精彩评论