getResource in order to get the top-level resource directory?

Hi all. Been converting a project from maven to Gradle and ran into something that seems a little inconsistent but maybe I’m just doing something wrong.

I have the following snippet in a unit test:

final URL resDir = getClass().getClassLoader().getResource(".");
final URL otherThing = getClass().getClassLoader().getResource("specific_file.json");
System.out.println("wow cool " + resDir);
System.out.println("wow cool! " + otherThing);

Which ends up with the following output when running tests through gradle:

wow cool file:/mnt/dev/gauntlet_3/cat/build/classes/scala/test/
wow cool! file:/mnt/dev/gauntlet_3/cat/build/resources/test/specific_file.json

Where “cat” is the sub-project.

I have a few json files sitting at the top-level of src/test/resources, and I need to pass that directory to something I’m testing, because it’s expected to load json files based on names passed in later on.

Why does getting the directory go to classes, but getting a specific file goes to resources? I’ve tried “/” as well.

For now I’ve worked around it by getting the specific file and then using .getParentFile(), which is fine, but I’m wondering if there’s a better way to do this.

I can’t say I’ve ever tried getting the resource “.”

There’s likely multiple roots (one for classes root, another for resources root and maybe one for every jar too?). Classloader.getResource(".") is likely returning the first.

You can get an Enumeration<URL> via Classloader.findResources(".")

If you want resources root, I suggest finding a known resource and work up to the root from there. Or have gradle inject it into the jvm for you (assuming test only)

Is there a particular reason why you need a File and can’t make do with Classloader instead? Ultimately your class is likely to be inside a jar in production, not in a folder

Yeah, going up works fine and I’ll probably just stick with that. My class does end up in a jar, but these config files exist outside of the jar itself… and in any case this is just for loading test resources anyways.