简体   繁体   English

未从 Gradle 项目中找到 Intellij 资源

[英]Intellij resource not found from Gradle Project

I'm having a library (which is built with Gradle 7.4) with a structure like this:我有一个库(用 Gradle 7.4 构建),其结构如下:

|
|- src
| -  main
| - - java
| - - resources

In this library, I have a class which loads a resource file like this:在这个库中,我有一个 class 加载这样的资源文件:

var resource=this.getClass().getResource("sample.properties");

My sample.properties file is placed under src/main/resources我的 sample.properties 文件放在 src/main/resources 下

When building the library, Gradle is placing the compiled classes under build/classes/java/main and resources under build/resources/main.构建库时,Gradle 将编译后的类放在 build/classes/java/main 下,资源放在 build/resources/main 下。

Now, I have a Application, which is a non-Gradle project and has a module dependency to my Library.现在,我有一个应用程序,它是一个非 Gradle 项目并且对我的库具有模块依赖性。 My Application uses the Library, which then loads the resource file.我的应用程序使用库,然后加载资源文件。 Now, when I run my Application, the debugger states that it looks for the resource file under build/classes/java/main/mypackage/sample.properties.现在,当我运行我的应用程序时,调试器声明它在 build/classes/java/main/mypackage/sample.properties 下查找资源文件。

But, as stated before, the resource is under build/resources/main.但是,如前所述,该资源位于 build/resources/main 下。
The resource afterwards is null.后面的资源是null。
My Question: How can my Library load my resource file accordingly?我的问题:我的图书馆如何相应地加载我的资源文件?

Update 24.11: I forgot to mention that this worked with Eclipse (because it copies classes and resources to the same dir) but not with Intellij and now I'm trying to fix this with Intellij IDEA.更新 24.11:我忘了提到这适用于 Eclipse(因为它将类和资源复制到同一目录)但不适用于 Intellij,现在我正在尝试使用 Intellij IDEA 修复此问题。

If the parent application which uses your library (which requires some resource files) is a non-gradle/non-maven project being built/compiled/run using plain java commands.如果使用您的库(需要一些资源文件)的父应用程序是一个非 gradle/非 Maven 项目,正在使用普通 java 命令构建/编译/运行。

You can try to supply the resource folder externally as a classpath (using -cp option) in the java commands您可以尝试在java命令中将资源文件夹作为类路径从外部提供(使用-cp选项)

java -cp /path/to/resource application.jar

Another option would be to ask for the resource file explicitly in the library APIs (methods, class constructors etc.) which needed to be supplied by the user of the library (parent application).另一种选择是在库 API(方法、class 构造函数等)中显式请求资源文件,这需要由库的用户(父应用程序)提供。 This will eliminate runtime crashes on missing files at a pre-defined path.这将消除在预定义路径中丢失文件时的运行时崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM