如何从groovy jar库中的资源目录中获取文件

时间:2018-03-15 13:36:57

标签: gradle intellij-idea groovy jar resources

我无法从我项目的编译jar中读取JSON目录中的resources文件。

但......首先要做的事情是:

我在Intellij idea(v2017.3.4 Community Edition)中创建了一个'Gradle Groovy'项目,其结构如下:

enter image description here

因此,正如您所看到的,我在Main.groovy目录中只有一个resources类和一个src/main文件夹。

resources目录中,我只有一个资源db/products.json

通过进入File > Project Structure > Modules > Project Module > Sources菜单,我们可以检查src/groovy文件夹是否已标记为Sourcesresources文件夹已标记为Resource Folder,因此我可以保证此文件夹已在classpath上正确设置:

enter image description here

在我的Main类中,我添加了以下代码行来加载/db/products.json资源:

enter image description here

通过在Intellij中运行项目,我可以检查资源是否无缝加载:

enter image description here

大!但...

现在抓住了!

当我用gradle - 通过gradlew build命令编译项目时,jar ReadJSONResourceFile-1.0-SNAPSHOTbuild/libs文件夹中生成。

查看jar的结构,我们可以检查db资源文件夹是否位于jar的根位置:

enter image description here

但是当我通过命令执行jar时:

groovy -cp build/libs/ReadJSONResourceFile-1.0-SNAPSHOT.jar -e "org.company.demo.Main.main()"

资源未成功加载。 getResource()只返回null

enter image description here

我一直在尝试使用Stack Overflow上提供的其他解决方案解决此问题,但这些解决方案都没有奏效。

我在这里错过了什么......你能帮忙吗?

0 个答案:

没有答案