使用类从外部模块加载资源文件

Abu*_*akr 5 java

我在尝试从外部模块的资源文件夹加载资源文件时遇到困难。我正在使用 IntelliJ,我们的项目是使用 Maven 构建的。

使用模块之前的原始代码是这样的:

getClass().getResourceAsStream(rulesFile)

这现在产生了null结果。


模块的结构如下:

client
    - java
        - org.example.client
            - Controller.java

data
    - java
        - ...
    - resources
        - org.example.data.files
            - rulesFile

Run Code Online (Sandbox Code Playgroud)

在模块中client

getClass().getResourceAsStream(rulesFile) 不起作用。

但是,如果我尝试去做ModuleLayer.boot().findModule("data").get().getResourceAsStream(rulesFile),那么它工作正常。

我的问题是,是否可以使模块内部rulesFile可见,以便可以使用普通的类加载器?我想避免必须明确指定它来自的模块名称,因为在其他地方使用了从模块加载文件的类似代码。Controller.javaclientdata

我有哪些选项可以避免显式给出模块名称?

我尝试将以下内容添加到data模块文件中,但没有成功:

opens org.example.data.files to client

谢谢您的帮助!

小智 2

http://maven.apache.org/pom.html#Resources

在您的客户端模块 pom.xml 中添加:

<project>
    ...

    <build>
    ...

        <resources>
            <resource>
                <directory>../data/src/main/resources/org/example/data/files</directory>
                <includes>
                    <include>rulesFile</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>
Run Code Online (Sandbox Code Playgroud)