Is it possible load all properties files contained in a package dynamically? i.e. MyClass.class.getResource('*.properties');

橙三吉。 提交于 2019-12-06 03:08:41

问题


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 in the same package as my class?


回答1:


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.




回答2:


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.




回答3:


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
    }
}


来源:https://stackoverflow.com/questions/2960355/is-it-possible-load-all-properties-files-contained-in-a-package-dynamically-i-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!