Andrea
Andrea

Reputation: 20493

Gradle - Handling external resources

I am trying to move a simple Groovy project to Gradle. I was mostly able to configure the project, but I do not know how to deal with external resources.

Basically, my application needs to access a configuration file in JSON. Before moving to Gradle, I used to pass the location of this JSON file on the command line. I had made a simple bash script to call the main class with the correct path for the resource.

With Gradle if I understand correctly, I should be able to move this file into src/main/resources/ and have it available somehow from the Groovy classes. Question is: how?

EDIT

If I understand correctly, the resource should end in the JAR that gets built. My dir structure is like

src
  main
    groovy
      orgName
        packageName
          source.groovy
    resources
      orgName
        packageName
          config.json

But I do not see the resource inside the packageName.jar that is generated in the build directory

Upvotes: 3

Views: 7598

Answers (2)

tim_yates
tim_yates

Reputation: 171054

I knocked up a quick example... Given this directory structure:

.
|-- src
|    |-- main
|         |-- groovy
|         |    \-- org
|         |         |-- Test.groovy
|         \-- resources
|              \-- config.json
\-- build.gradle

Where Test.groovy is:

package org

import groovy.json.*

public class Test {
  static main( args ) {
    def slurper = new JsonSlurper()
    def config = slurper.parseText( Test.class.getResource( '/config.json' ).text )
    println "Args were $args, config is $config"
  }
}

config.json is:

{
  "data": true
}

and build.gradle is:

apply plugin: 'groovy'

repositories {
  mavenCentral()
}

dependencies {
  groovy 'org.codehaus.groovy:groovy-all:2.0.0'
}

task runTest ( dependsOn: 'classes', type: JavaExec ) {
  main = 'org.Test'
  classpath = sourceSets.main.runtimeClasspath
  args 'ARG1'
}

You should just be able to run gradle runTest and it should just work...

Upvotes: 8

Peter Niederwieser
Peter Niederwieser

Reputation: 123890

Gradle doesn't mandate that you treat the file as a resource. It's just a Java/JVM best practice. If you do so, you'll have to access the file via a class loader. See Locating resources in Java for an explanation. Note that this is unrelated to Gradle, except that Gradle will add files under src/main/resources to the Jar that gets built.

Upvotes: 2

Related Questions