如何在Java 9模块中使用资源 [英] How to work with resources in Java 9 modules
问题描述
I built a small (hello world style) java 9 project using gradle and the jigsaw plugin.
对于junit测试,我尝试将某些文件作为资源进行访问,但是classLoader.getResource(filename)
无法找到该文件.
For a junit test I tried to access some file as a resource, but classLoader.getResource(filename)
is not able to locate the file.
通常,您将文件放置为src/test/resources/foo.txt
并以/foo.txt
对其进行访问,但是在Java 9中,看起来情况发生了变化,资源也很(类似于类)
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.
我应该在哪里正确放置gradle的资源文件以正确打包?
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? :)
更准确地说,我设置了一个小的测试项目.
使用git clone https://github.com/michas2/java_9_resource_test.git
,并在更改到该目录之后执行gradle build
. (我正在使用gradle 4.6,但这不应该是问题.)
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.)
结构如下:
.
├── build.gradle
└── src
├── main
│ └── java
│ ├── module-info.java
│ └── resourceTest
│ └── Main.java
└── test
├── java
│ └── resourceTest
│ └── MainTest.java
└── resources
└── resourceTest
└── test.txt
我尝试使用this.getClass().getResource("/resourceTest/test.txt")
访问资源,不幸的是,该资源却返回null
.
I try to access the resource using this.getClass().getResource("/resourceTest/test.txt")
, which unfortunately gives null
in return.
推荐答案
这似乎是Gradle的错误.
This appears to be a Gradle bug.
当我使用-i
选项运行Gradle时,我看到它为运行程序而执行的实际命令包括以下内容:
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
如您所见,它包括build/classes
目录,但不包括build/resources
目录.
As you can see, it’s including the build/classes
directory, but not the build/resources
directory.
由于构建将类和资源放置在单独的位置,因此无法使用--patch-module
.这些类和资源必须一起放在一个文件树或一个.jar文件中.
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.
我不确定org.gradle.java.experimental-jigsaw插件或Gradle本身是否有缺陷.
Whether this is a flaw in the org.gradle.java.experimental-jigsaw plugin, or Gradle itself, I’m not sure.
这篇关于如何在Java 9模块中使用资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!