从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,但是对于InputStream是假的。
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屋!