如何正确使用ClassLoader.getResources()? [英] How to use ClassLoader.getResources() correctly?

查看:2311
本文介绍了如何正确使用ClassLoader.getResources()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 ClassLoader.getResources()从我的类路径中查找recursivly资源?

How can I use ClassLoader.getResources() to find recursivly resources from my classpath?

例如。


  • 查找 META-INF 目录中的所有资源:
    想象一下像

  • finding all resources in the META-INF "directory": Imagine something like

getClass()。getClassLoader()。getResources(META-INF)

不幸的是,这只会将 URL 检索到这个目录。

Unfortunately, this does only retrieve an URL to exactly this "directory".

名为 bla.xml的所有资源(recursivly)

all resources named bla.xml (recursivly)

getClass()。getClassLoader()。getResources(bla.xml)

但这会返回一个空的枚举

作为奖励问题:如何 ClassLoader.getResources()不同ClassLoader.getResource()

And as a bonus question: How does ClassLoader.getResources() differ from ClassLoader.getResource()?

推荐答案

无法以递归方式搜索类路径。您需要知道资源的完整路径名才能以这种方式检索它。资源可能位于文件系统的目录中或jar文件中,因此它不像执行类路径的目录列表那么简单。您需要提供资源的完整路径,例如'/com/mypath/bla.xml'。

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'.

对于第二个问题,getResource将返回与给定资源名称匹配的第一个资源。搜索类路径的顺序在 getResource的javadoc。

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.

这篇关于如何正确使用ClassLoader.getResources()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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