How to work with resources in Java 9 modules

心不动则不痛 提交于 2019-12-31 02:15:26

问题


I built a small (hello world style) java 9 project using gradle and the jigsaw plugin.

For a junit test I tried to access some file as a resource, but classLoader.getResource(filename) is not able to locate the file.

Usually you put the file as src/test/resources/foo.txt and access it as /foo.txt, but with Java 9 it looks like things changed and resources are (similar like classes) encapsulated in modules.

Where exactly do I have to put the resource file for gradle to package it correctly?

What is the right way to access that file afterwards in the test?

What is the documentation I forgot to read? :)


To be more precise I set up a small test project. Use git clone https://github.com/michas2/java_9_resource_test.git and do a gradle build afterwards after changing to that directory. (I'm using gradle 4.6, but that should not be the problem.)

The structure looks like this:

.
├── build.gradle
└── src
    ├── main
    │   └── java
    │       ├── module-info.java
    │       └── resourceTest
    │           └── Main.java
    └── test
        ├── java
        │   └── resourceTest
        │       └── MainTest.java
        └── resources
            └── resourceTest
                └── test.txt

I try to access the resource using this.getClass().getResource("/resourceTest/test.txt"), which unfortunately gives null in return.


回答1:


This appears to be a Gradle bug.

When I run Gradle with the -i option, I see that the actual command it’s executing to run your program includes this:

--patch-module resourceTest=/home/vgr/src/java_9_resource_test/build/classes/java/test

As you can see, it’s including the build/classes directory, but not the build/resources directory.

Since the build places the classes and resources in separate places, there is no way to use --patch-module. The classes and resources must be together, in one file tree or one .jar file.

Whether this is a flaw in the org.gradle.java.experimental-jigsaw plugin, or Gradle itself, I’m not sure.



来源:https://stackoverflow.com/questions/49678324/how-to-work-with-resources-in-java-9-modules

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