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 rece开发者_运维知识库ived 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?
URLs are your friend
URL.openStream
.
Fortunately, the desicion with the "!" symbol doesn't work.
Have a look here:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4730642
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).
try using java.net.JarURLConnection
URL url = new URL("jar:file:C:\mydir\my.jar!\myresource.txt");
JarURLConnection jarConnection = (JarURLConnection)url.openConnection();
private InputStream twistLid(File jar, String resource) throws IOException {
return new URL("jar:" + jar.toURI() + "!" + resource).openStream();
}
Building on the work of many above, here's an example in groovy, listing the text contained in 'resource.txt' inside a folder named 'reources' at the root level of a 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)
}
精彩评论