开发者

Getting resources from jar in a java webstart application

开发者 https://www.devze.com 2023-04-02 06:15 出处:网络
I am trying to load a number of resources in a Java webstart application. I had originally tried to load these using:

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());

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:

Cl开发者_如何学编程assLoader loader = MyClass.class.getClassLoader();
InputStream in = loader.getResourceAsStream("resourceName");

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);
}

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.

Any ideas on what I might be doing wrong? Are there better ways of loading resources for use in the java webstart application?

Edit: For info, my resources are in MyProject/src/main/resources, and when the jar is generated, the resources are in the jar root.


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 = url.openStream();
  System.out.println(in!=null);
}


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).

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.

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.


you needy to add the class path in your manifest file

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号