如何正确使用ClassLoader.getResources()?

发布于 2024-10-20 01:37:01 字数 524 浏览 7 评论 0原文

如何使用 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 like

    getClass().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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

吾家有女初长成 2024-10-27 01:37:01

Spring 框架有一个类,允许递归搜索类路径:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");
三生池水覆流年 2024-10-27 01:37:01

无法递归搜索类路径。您需要知道资源的完整路径名才能以这种方式检索它。该资源可能位于文件系统的目录中或位于 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.

我做我的改变 2024-10-27 01:37:01

这是获取某个 URL 对象指向的 File 对象的最简单方法:

File file=new File(url.toURI());

现在,针对您的具体问题:

  • 查找 META-INF“目录”中的所有资源:

确实可以获得指向此 URL 的 File 对象

Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
    URL metaInf=en.nextElement();
    File fileMetaInf=new File(metaInf.toURI());

    File[] files=fileMetaInf.listFiles();
    //or 
    String[] filenames=fileMetaInf.list();
}
  • 所有名为 bla.xml 的资源
    (递归地)

在这种情况下,您必须执行一些自定义代码。这是一个虚拟示例:

final List<File> foundFiles=new ArrayList<File>();

FileFilter customFilter=new FileFilter() {
    @Override
    public boolean accept(File pathname) {

        if(pathname.isDirectory()) {
            pathname.listFiles(this);
        }
        if(pathname.getName().endsWith("bla.xml")) {
            foundFiles.add(pathname);
            return true;
        }
        return false;
    }

};      
//rootFolder here represents a File Object pointing the root forlder of your search 
rootFolder.listFiles(customFilter);

运行代码时,您将在 foundFiles 列表中获取所有找到的事件。

This is the simplest wat to get the File object to which a certain URL object is pointing at:

File file=new File(url.toURI());

Now, for your concrete questions:

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

You can indeed get the File object pointing to this URL

Enumeration<URL> en=getClass().getClassLoader().getResources("META-INF");
if (en.hasMoreElements()) {
    URL metaInf=en.nextElement();
    File fileMetaInf=new File(metaInf.toURI());

    File[] files=fileMetaInf.listFiles();
    //or 
    String[] filenames=fileMetaInf.list();
}
  • all resources named bla.xml
    (recursivly)

In this case, you'll have to do some custom code. Here is a dummy example:

final List<File> foundFiles=new ArrayList<File>();

FileFilter customFilter=new FileFilter() {
    @Override
    public boolean accept(File pathname) {

        if(pathname.isDirectory()) {
            pathname.listFiles(this);
        }
        if(pathname.getName().endsWith("bla.xml")) {
            foundFiles.add(pathname);
            return true;
        }
        return false;
    }

};      
//rootFolder here represents a File Object pointing the root forlder of your search 
rootFolder.listFiles(customFilter);

When the code is run, you'll get all the found ocurrences at the foundFiles List.

﹏雨一样淡蓝的深情 2024-10-27 01:37:01

这是基于 bestsss 答案的代码:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }
唯憾梦倾城 2024-10-27 01:37:01

MRalwasser,我给你一个提示,将 URL.getConnection() 转换为 JarURLConnection
然后使用 JarURLConnection.getJarFile() 瞧!您拥有 JarFile,并且可以自由访问其中的资源。

剩下的我就留给你了。

希望这有帮助!

MRalwasser, I'd give you a hint, cast the URL.getConnection() to JarURLConnection.
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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文