如何遍历Java类资源? [英] How to walk through Java class resources?

查看:95
本文介绍了如何遍历Java类资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以这样做:

I know we can do something like this:

Class.class.getResourceAsStream("/com/youcompany/yourapp/module/someresource.conf")

读取打包在我们jar文件中的文件。

to read the files that are packaged within our jar file.

我在Google上搜索了很多,并且我肯定没有使用正确的术语;我想做的是列出可用资源,例如:

I have googled it a lot and I am surely not using the proper terms; what I want to do is to list the available resources, something like this:

Class.class.listResources("/com/yourcompany/yourapp")

这应该返回包<$ c $内的资源列表c> com.yourcompany.yourapp。*

有可能吗?如果无法像我展示的那样容易完成,该如何做呢?

Is that possible? Any ideas on how to do it in case it can't be done as easily as I showed?

注意:我知道有可能知​​道您的罐子在哪里,并且然后打开它并检查其内容以实现它。但是,我无法在现在正在使用的环境中这样做。

Note: I know it is possible to know where your jar is and then open it and inspect its contents to achieve it. But, I can't do it in the environment I am working in now.

推荐答案

对于JAR文件中的资源,有些东西像这样工作:

For resources in a JAR file, something like this works:

URL url = MyClass.class.getResource("MyClass.class");
String scheme = url.getProtocol();
if (!"jar".equals(scheme))
  throw new IllegalArgumentException("Unsupported scheme: " + scheme);
JarURLConnection con = (JarURLConnection) url.openConnection();
JarFile archive = con.getJarFile();
/* Search for the entries you care about. */
Enumeration<JarEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
  JarEntry entry = entries.nextElement();
  if (entry.getName().startsWith("com/y/app/")) {
    ...
  }
}

您可以使用文件系统或许多其他存储库中爆炸的资源来执行相同的操作,但这并不那么容易。您需要为每个要支持的URL方案指定特定的代码。

You can do the same thing with resources "exploded" on the file system, or in many other repositories, but it's not quite as easy. You need specific code for each URL scheme you want to support.

这篇关于如何遍历Java类资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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