How do I add resources to sourceSet with gradle?

懵懂的女人 提交于 2019-12-29 04:09:05

问题


Currently I have the following build.gradle file:

apply plugin: 'java'

repositories {
    mavenCentral()
}

sourceSets {
    main {
        java {
            srcDir 'src/model'
        }
        resources {
            srcDir 'images/model' 
        }
    }

    test {
        java {
            srcDir 'tests/model'
        }
        resources {
            srcDir 'images/model' // <=== NOT WORKING
        }
    }
}

dependencies {
    compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
    runtime fileTree(dir: 'libs', include: '*.jar')

    testCompile group: 'junit', name: 'junit', version: '4.+'
}

My repository if here: https://github.com/quinnliu/WalnutiQ

and 4 out of my 49 tests are failing because the tests in folder "tests/model" need a file within the folder "images/model". How do I add the resources correctly? Thanks!


回答1:


I had a closer look at your build.gradle and it seems that paths are a little bit off.

You specify source as src/model, yet your project structure and Java source suggest that model is your package name, which means the source declaration should be:

main {
    java {
        srcDir 'src'
    }
}

Same for tests:

test {
    java {
        srcDir 'tests'
    }
}

Now, with missing resources. In your code you are using ImageIO.read(getClass().getResource(BMPFileName))
getClass().getResource() is using relative path to the resource. To keep the resources on the same level, you should update declaration for the resources and remove model:

test {
    java {
        srcDir 'tests'
    }
    resources {
        srcDir 'images'
    }
}

You might also need to run

./gradlew clean

before it works.

Here's the result with the updated build.gradle:

Hope it helps :)




回答2:


The syntax used in your build script is correct. It's not clear to me why you add the same resource directory to both source sets, and why you claim that it isn't working in one case.

srcDir "foo" adds another directory. If you instead want to replace the default directory, use srcDirs = [ "foo" ] instead. However, this won't solve the problem at hand.

It would be good to see the code that loads the resources, to rule out any problems with that.



来源:https://stackoverflow.com/questions/20732206/how-do-i-add-resources-to-sourceset-with-gradle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!