如何在jar文件中使用ClassLoader.getResources() [英] How to use ClassLoader.getResources() in jar file

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

问题描述

问题陈述:

我有一个包含一组配置文件的jar文件 mycompany / configuration / file / 。 />
我不知道文件名。

我的目的是在运行时从打包它们的jar文件中加载文件名,然后在我的应用程序中使用它。

据我所知:
当我使用 ClassLoader.getResources(mycompany / configuration / file /)我应该将所有配置文件作为URL获取。

然而,这就是发生的事情:

我得到一个带URL的URL对象,如 jar:file :/ C:/myJarName.jar!mycompany / configuration / file /

你能否让我知道我做错了什么?

Problem statement:
I have a jar file with a set of configuration files in a package mycompany/configuration/file/.
I don't know the file names.
My intention is to load the file names at runtime from the jar file in which they are packaged and then use it in my application.
As far as I understood: When I use the ClassLoader.getResources("mycompany/configuration/file/") I should be getting all the configuration files as URLs.
However, this is what is happening:
I get one URL object with URL like jar:file:/C:/myJarName.jar!mycompany/configuration/file/
Could you please let me know what I am doing wrong ?

推荐答案

对于你想要做的事情,我认为不可能。

For what you are trying to do I don't think it is possible.

getResource getResources 是关于在类加载器的类路径中查找命名资源,而不是列出目录或文件夹下的值。

getResource and getResources are about finding named resources within the classloader's classpath, not listing values beneath a directory or folder.

例如 ClassLoader.getResources(mycompany / configuration / file / Config.cfg)将返回类加载器类路径中 mycompany / configuration / file 路径中存在的名为 Config.cfg 的所有文件(我发现这对于个人加载版本信息。)

So for example ClassLoader.getResources("mycompany/configuration/file/Config.cfg") would return all the files named Config.cfg that existed in the mycompany/configuration/file path within the class loader's class path (I find this especially useful for loading version information personally).

在您的情况下,我认为您可能几乎有半个解决方案。您获取的URL包含源jar文件(jar:file:/ C:/myJarName.jar)。您可以使用此信息来破解打开jar文件,读取条目列表,过滤那些名称以mycompany / configuration / file /\".

In your case I think you might almost have half a solution. The URL you are getting back contains the source jar file (jar:file:/C:/myJarName.jar). You could use this information to crack open the jar file a read a listing of the entries, filtering those entries whose name starts with "mycompany/configuration/file/".

开头的条目从那里,你可以回到 getResource 方法来加载对每个方法的引用(现在你有了名字和路径)

From there, you could then fall back on the getResource method to load a reference to each one (now that you have the name and path)

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

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