简体   繁体   English

将JAR资源作为FileStream打开

[英]Opening a JAR resource as a FileStream

I have a project where I want to access a resource in a JAR from another project. 我有一个项目,我想从另一个项目访问JAR中的资源。 It's not on my classpath, so ClassLoader is not an option. 它不在我的类路径上,所以ClassLoader不是一个选项。 I tried: 我试过了:


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

and received a FileNotFoundException. 并收到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). JarInputStream可能是一种可能,但我希望输入文件名的灵活性是jar资源,或者只是系统上的文件(用户决定)。 Is there a class that can do this or do I have to build one myself? 是否有一个类可以做到这一点,还是我必须自己构建一个?

URLs are your friend 网址是你的朋友

URL.openStream . 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 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4730642

Try using a URLClassLoader . 尝试使用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). 我之前做过类似的事情,它似乎有效(尽管你可能需要使用安全策略文件,如果你在一个安全的JVM中)。

try using java.net.JarURLConnection 尝试使用java.net.JarURLConnection

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

JarURLConnection jarConnection = (JarURLConnection)url.openConnection(); 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 在上面的许多工作的基础上,这是groovy中的一个例子,在jar文件根级别的名为'reources'的文件夹中列出'resource.txt'中包含的文本

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM