如何正确使用ClassLoader.getResources()?
如何使用 ClassLoader.getResources() 从类路径中查找递归资源?
例如
查找
META-INF
“目录”中的所有资源: 想象一下类似的事情getClass().getClassLoader().getResources("META-INF")
不幸的是,这只能检索到这个“目录”的
URL
。所有名为
bla.xml
的资源(递归)getClass().getClassLoader().getResources("bla.xml")
但这会返回一个空的
Enumeration
。
还有一个额外问题:ClassLoader.getResources()
与 ClassLoader.getResource()
有何不同?
How can I use ClassLoader.getResources()
to find recursivly resources from my classpath?
E.g.
finding all resources in the
META-INF
"directory":
Imagine something likegetClass().getClassLoader().getResources("META-INF")
Unfortunately, this does only retrieve an
URL
to exactly this "directory".all resources named
bla.xml
(recursivly)getClass().getClassLoader().getResources("bla.xml")
But this returns an empty
Enumeration
.
And as a bonus question: How does ClassLoader.getResources()
differ from ClassLoader.getResource()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Spring 框架有一个类,允许递归搜索类路径:
The Spring Framework has a class which allows to recursively search through the classpath:
无法递归搜索类路径。您需要知道资源的完整路径名才能以这种方式检索它。该资源可能位于文件系统的目录中或位于 jar 文件中,因此它不像执行“类路径”的目录列表那么简单。您需要提供资源的完整路径,例如“/com/mypath/bla.xml”。
对于第二个问题, getResource 将返回与给定资源名称匹配的第一个资源。搜索类路径的顺序在 getResource 的 javadoc。
There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.
For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.
这是获取某个 URL 对象指向的 File 对象的最简单方法:
现在,针对您的具体问题:
确实可以获得指向此 URL 的 File 对象
在这种情况下,您必须执行一些自定义代码。这是一个虚拟示例:
运行代码时,您将在
foundFiles
列表中获取所有找到的事件。This is the simplest wat to get the File object to which a certain URL object is pointing at:
Now, for your concrete questions:
You can indeed get the File object pointing to this URL
In this case, you'll have to do some custom code. Here is a dummy example:
When the code is run, you'll get all the found ocurrences at the
foundFiles
List.这是基于 bestsss 答案的代码:
Here is code based on bestsss' answer:
MRalwasser,我给你一个提示,将
URL.getConnection()
转换为JarURLConnection
。然后使用 JarURLConnection.getJarFile() 瞧!您拥有 JarFile,并且可以自由访问其中的资源。
剩下的我就留给你了。
希望这有帮助!
MRalwasser, I'd give you a hint, cast the
URL.getConnection()
toJarURLConnection
.Then use JarURLConnection.getJarFile() and voila! You have the JarFile and you are free to access the resources inside.
The rest I leave to you.
Hope this helps!