简体   繁体   English

如何从打包到自己的.jar中的java库访问资源

[英]How to access a resource from a java library packed into its own .jar

I have a library project with some resources that I would like to load and use. 我有一个库项目,其中包含一些我想加载和使用的资源。 I would be using this library in another project so I have to pack the resources into the .jar. 我会在另一个项目中使用这个库,所以我必须将资源打包到.jar中。 This is how that's achieved: 这是如何实现的:

<resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

The problem comes when trying to retrieve the file, I do: 尝试检索文件时出现问题,我这样做:

String resourceName = "myTemplateResource.json";
URL url = MyClass.class.getClassLoader().getResource(resourceName);

url is assigned a null value. url被赋予null值。 It happens in the library's tests and in the dependant project. 它发生在库的测试和依赖项目中。 Any hint of what is missing? 什么缺失的暗示?

Also tested using 也测试使用

MyClass.class.getResource("/myTemplateResourceName.json");

and

MyClass.class.getClassLoader().getResource("src/main/resources/myTemplateResource.json");

with the same result. 结果相同。

Use getResourceAsStream() method to load the resource from the .jar file as follows: 使用getResourceAsStream()方法从.jar文件加载资源,如下所示:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(locaiton);

eg: If the file 'myTemplateResourceName.json' is located directly in the resources folder, use only the file name. 例如:如果文件'myTemplateResourceName.json'直接位于resources文件夹中,请仅使用文件名。 It is wrong if you add a slash (/) in front of the path. 如果在路径前添加斜杠(/),则会出错。

InputStream inputStream = classLoader.getResourceAsStream("myTemplateResourceName.json");

Note: You have to place the resource file in the main/resources (don't keep it in the test/resources section since that is not packed in the jar file) folder in the project which is being used to create the jar file. 注意:您必须将资源文件放在main/resources (不要将它保存在test/resources部分,因为它没有打包在jar文件中)文件夹中用于创建jar文件的项目。

There was something wrong with the filename that I was not able to find out. 文件名有问题,我无法找到。 Renamed the file and now it's fine. 重命名文件,现在没关系。

To answer my question: 回答我的问题:

First add the resource to the jar on the .pom file. 首先将资源添加到.pom文件上的jar中。

<resources>
    <resource>
        <directory>src/main/resources</directory>
    </resource>
</resources>

Then access your file. 然后访问您的文件。

URL url = MyClass.class.getClassLoader().getResource(resourceName);

From there you can get an InputStream . 从那里你可以得到一个InputStream As simple as it looks. 看起来很简单。

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

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