How do I use getResources with a gradle project?

(Jason Majors) #1

I have the following

apply plugin: 'war'
version = '1.0'
repositories {
  war {
  archiveName = 'querytags.war'
  dependencies {
  testCompile 'junit:junit:4.+'
  test {
  systemProperties 'db.user': 'root'

My directory structure is pretty standard:


I’m using JerseyTest and Grizzly to unit test my WAR. In the unit test, I want to load the testData.json file (which gets placed in build/resources/test/ ). I use the following code to do so:

String resource = "/testData.json";
String fileName = UnitTests.class.getClassLoader().getResource(resource).getFile();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{ ... }

But the getResource() call is returning null. Is there a setting in gradle that I need to use to allow getResources() to scan that directory? I tried adding the following to my build.gradle file, but it didn’t help:

sourceSets {
  test {
     output.resourcesDir = "build/resources/test"

(Peter Niederwieser) #2

It’s likely not a Gradle related problem. Instead, you need to get rid of the leading slash in the resource name.

PS: The best way to read the contents of a resource file is via ‘ClassLoader#getResourceAsStream’. If you must convert to a ‘File’, the recommended way to do so is ‘new File(classLoader.getResource(…).toURI())’.