views:

139

answers:

3

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  A: 

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.

BalusC
Sorry, no File allowed. Class is currently not in a jar... but I do not know what the future holds for my class and I have no control over the enviroment this will be run in, so it needs to be as decoupled as possible
Stoney
Sorry... don't have enough points to vote up ur answer yet...
Stoney
+1  A: 

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.

Istao
Curses, someone stole my thunder :) Have a cookie. +1
skaffman
A: 

This is how I did it,

    Class<? extends Object> clazz = AnyKnownClassInTheJar.class;
    String className = clazz.getSimpleName() + ".class";
    String classPath = clazz.getResource(className).toString();
    if (!classPath.startsWith("jar")) {
      // Class not from JAR
      return;
    }
    URL url = new URL(classPath);
    JarURLConnection conn = (JarURLConnection)url.openConnection();
    JarFile jf = conn.getJarFile();
    for (Enumeration<JarEntry> i = jf.entries(); i.hasMoreElements();) {
        JarEntry je = i.nextElement();
        String name = je.getName();
        if (name.indexOf(".properties") != -1) {
            // Load the property file
        }
    }
ZZ Coder