使用java.lang.Class.getResources [英] Use of java.lang.Class.getResources

查看:373
本文介绍了使用java.lang.Class.getResources的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到一些关于使用 java.lang.Class.getResources() java.lang.Class.getResourcesAsStream / code> on SO今天。



我有一个包含此结构的Jar文件(resources / test.xml)



这个jar文件在我的应用程序的类路径上,当我调用下面的代码片段时,它返回null,即mappingURL的值为null。

  URL mappingURL = this.getClass()。getResource(/ resources / test.xml);然而,当我以分解格式将XML文件存储在类路径上时,即通过创建一个目录resources来存储XML文件, 



我使用这个URL稍后读取test.xml文件的内容。



这是否意味着, getResources()不是从Jar中读取文件的适当方法?我不明白为什么 mappingURL 在文件(test.xml)存在于Jar文件中时为空?

解决方案

getResource()方法将返回 null 资源。您正在为资源添加 / 前缀,这意味着它正在尝试查找文件夹。您应该可以移除领导 / ,并达到预期效果。



这里是 getResource()方法描述:


查找具有给定名称的资源。资源是可以通过类代码以独立于代码的位置的方式访问的一些数据(图像,音频,文本等)。



资源的名称是一个以/分隔的路径名称,用于标识资源。



此方法将首先搜索父类加载器的资源;如果父为null,则搜索虚拟机内置的类加载器的路径。那个失败,这个方法将调用findResource(String)来查找资源。



I've seen some posts on using java.lang.Class.getResources() and java.lang.Class.getResourcesAsStream() on SO today. Somehow, I still have confusion.

I have a Jar file that contains this structure (resources/test.xml)

This jar file is on the classpath of my application, and when I call below piece of code, it returns null, i.e. value of mappingURL is null.

 URL mappingURL = this.getClass().getResource("/resources/test.xml");

However when I store the XML file in exploded format on the classpath i.e. by creating a directory "resources" and storing mapping.xml inside, it works.

I'm using this URL for reading the content of the "test.xml" file later.

Does that mean, getResources() is not the appropriate method for reading the files from inside a Jar? I didn't understand why mappingURL is null when file (test.xml) is present in the Jar file?

解决方案

The getResource() method will return null if it cannot find the resource. You are prefixing the resource with a / which means that it is trying to look in the folder. You should be able to remove the leading / and achieve your intended result.

Here is the getResource() method description from the documentation:

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

这篇关于使用java.lang.Class.getResources的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆