tags:

views:

133

answers:

5

I have a project where I want to access a resource in a JAR from another project. It's not on my classpath, so ClassLoader is not an option. I tried:


new FileInputStream("C:\\mydir\\my.jar!\\myresource.txt");

and received a FileNotFoundException.

JarInputStream might be a possibility, but I want the flexibility of the input filename being a jar resource or just a file on the system (user decides). Is there a class that can do this or do I have to build one myself?

+3  A: 

URLs are your friend

URL.openStream.

Tom Hawtin - tackline
A: 

Try using a URLClassLoader. I've done something similar to this before, and it seems to work (though you may need to muck around with your security policy file, if you're in a secure JVM).

Jack Leow
+1  A: 

Fortunately, the desicion with the "!" symbol doesn't work.

Have a look here:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4730642

zeroed
+1 Very insightful. Thank you.
User1
A: 

try using java.net.JarURLConnection

URL url = new URL("jar:file:C:\mydir\my.jar!\myresource.txt");

JarURLConnection jarConnection = (JarURLConnection)url.openConnection();

Laxmikanth Samudrala
A: 
  private InputStream twistLid(File jar, String resource) throws IOException {
    return new URL("jar:" + jar.toURI() + "!" + resource).openStream();
  }
McDowell