Opening a JAR resource as a FileStream

I have a project in which I want to access a resource in a JAR from another project. This is not for my class, so ClassLoader is not an option. I tried:


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

and got a FileNotFoundException.

JarInputStream may be an option, but I want the flexibility of the input file name to be a jar resource or just a file on the system (user decides). Is there a class that can do this, or should I build it myself?

+5
source share
6 answers

Your friend urls

URL.openStream.

+3
source

Fortunately, the mood with "!" symbol does not work.

Look at here:

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

+1

URLClassLoader. - , , , ( , JVM).

0
source

try using java.net.JarURLConnection

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

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

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

Based on the work of many of the above, here is an example in groovy containing the text contained in "resource.txt" inside a folder named "reources" at the root level of the jar file

import java.io.*
import java.util.*
import java.util.jar.*

def getJarResourceAsStream(String jarName, String resource) throws IOException {
    def resourceStr = 'jar:' + (new File(jarName)).toURI() + '!' + resource
    return new URL(resourceStr).openStream()
}

def inputStream = getJarResourceAsStream('/some/file/path/myJar.jar', '/resources/resource.txt')

def reader = new InputStreamReader(inputStream)
BufferedReader buffer = new BufferedReader(reader)
String line
while((line = buffer.readLine()) != null) {
    System.out.println(line)
}
0
source

All Articles