在 java webstart 应用程序中从 jar 获取资源 [英] Getting resources from jar in a java webstart application
问题描述
我正在尝试在 Java webstart 应用程序中加载大量资源.
I am trying to load a number of resources in a Java webstart application.
我最初尝试使用以下方法加载这些:
I had originally tried to load these using:
ClassLoader loader = MyClass.class.getClassLoader();
URL url = loader.getResource("resourceName");
File file = new File(url.toURI());
但这没有用——它抛出了一个 IllegalArgumentException.进一步的研究表明,这种方法不适用于从 jar 文件访问资源,我需要使用以下方法:
But this didn't work - it threw an IllegalArgumentException. Further research suggested that this approach doesn't work with accessing resources from jar files, and that I need to use the following approach:
ClassLoader loader = MyClass.class.getClassLoader();
InputStream in = loader.getResourceAsStream("resourceName");
但是,当我使用 Jnlp 运行它时,我得到了奇怪的结果.如果我运行以下命令:
However, I get odd results when I run this using from the Jnlp. If I run the following:
public static void main(String[] args) throws IOException, URISyntaxException {
ClassLoader loader = MyClass.class.getClassLoader();
String r = "resourceName";
URL url = loader.getResource(r);
System.out.println(url!=null);
InputStream in = loader.getResourceAsStream(r);
System.out.println(in!=null);
}
在我的 IDE 中,我得到真正的 &真的(正如我所料).从 jnlp 运行,URL 为 true,但 InputStream 为 false.
In my IDE, I get true & true (as I would expect). Running from the jnlp, I get true for the URL, but false for the InputStream.
关于我可能做错了什么的任何想法?有没有更好的方法来加载资源以在 java webstart 应用程序中使用?
Any ideas on what I might be doing wrong? Are there better ways of loading resources for use in the java webstart application?
有关信息,我的资源在 MyProject/src/main/resources 中,生成 jar 时,资源在 jar 根目录中.
For info, my resources are in MyProject/src/main/resources, and when the jar is generated, the resources are in the jar root.
推荐答案
好的 - 所以问题是我试图访问资源目录(即从我问题中的示例中,resourceName 是一个资源文件目录).
Ok - so the problem was that I was trying to access directory of resources (i.e. from the example in my question, resourceName is a directory of resource files).
虽然在大多数环境中(例如在 IDE 中)可以通过这种方式访问资源,但从 Java webstart 运行时则无法访问.
Whilst it is possible to access resources in this way in most environments (e.g. in an IDE), it is not possible when running from Java webstart.
我发现这个页面特别有用:http://lopica.sourceforge.net/faq.html#listresources
I found this page particularly helpful: http://lopica.sourceforge.net/faq.html#listresources
...并按照这种方法制作了一个资源目录,然后我可以遍历该目录以获取相关资源.
...and have followed that approach to make a catalogue of resources, that I can then iterate through to get the relevant resources.
这篇关于在 java webstart 应用程序中从 jar 获取资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!