How to read a directory from the runtime classpath?

Viewed 12384

My Java application needs to be able to find a myconfig/ directory which will be bundled inside the same JAR:

myjar.jar/
    com/
        me/
            myproject/
                ConfigLoader.java --> looks for myconfig/ directory and its contents
    myconfig/
        conf-1.xml
        conf.properties
        ... etc.

How do I actually go about reading this myconfig/ directory off the runtime classpath? I've done some research and it seems that the normal method of reading a file from the classpath doesn't work for directories:

InputStream stream = ConfigLoader.class.getResourceAsStream("myconfig");

So does anyone know how to read an entire directory from the runtime classpath (as opposed to a single file)? Thanks in advance!

Please note: It is not possible to load the files individually, myconfig is a directory with thousands of properties files inside it.

3 Answers

The trick seems to be that the class loader can find directories in the classpath, while the class can not.

So this works

this.getClass().getClassLoader().getResource("com/example/foo/myconfig");

while this does not

this.getClass().getResource("myconfig");
Related