Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use src/test/resources as directory with gradle java

I have got two working directories containing java code and resources, one is for testing and the other one is production.

src/main/java
src/main/resources

src/test/java
src/test/resources

When running my code and reading a file from FileInputStream like this:

new FileInputStream("./someFile.json");

As long a the file is located in the root of the project this works fine. It also works if I have the file in the resource folder and point directly to it like this:

new FileInputStream("src/test/resources/someFile.json");

Is there a way declaring src/test/resources in gradle as the main folder where FileInputStream looks for resources?

If i put my file like this it works fine.

enter image description here

But when I put the file in src/test/java/resources like this

enter image description here

I get a fileNotFoundException.

I need a way to add this directory to be scanned with gradle.



Adding this to build.gradle still throws a fileNotFoundException.

sourceSets {
test {
    java {
        srcDirs = ['src/test/java']
    }
    resources {
        srcDirs = ['src/test/resources']
        }
    }
}
like image 268
firozaqiwu Avatar asked Jun 30 '26 06:06

firozaqiwu


1 Answers

If you use the java or, since you seem to be building a command line application, the application plugin, everything will be set up for you out of the box:

plugins {
    id 'application'
}

You can remove all your sourceSet configurations and just load the file like so:

new FileInputStream("/someFile.json");

(Notice that I wrote / instead of ./ which changes the meaning from "look in the current directory, the project root" to "look in the root of a classpath resource".)
It would be even better to follow Slaw's comment under the question and locate the file via Class#getResourceAsStream(String) - but that's going beyond your question a bit.

like image 177
barfuin Avatar answered Jul 02 '26 21:07

barfuin