简体   繁体   English

从外部Jar文件中读取文件?

[英]Read a file from inside of an external Jar file?

I'm trying to read a file from inside an external jar using java.. For example, I have two jar files. 我正在尝试使用java从外部jar中读取文件。例如,我有两个jar文件。 One is "foo.jar" the other is "bar.jar". 一个是“foo.jar”,另一个是“bar.jar”。 Inside of "bar.jar" is the file "foo-bar.txt". “bar.jar”里面是文件“foo-bar.txt”。 How do i read the file "foo-bar.txt" from inside of "bar.jar" using code in "foo.jar"...? 如何使用“foo.jar”中的代码从“bar.jar”内部读取文件“foo-bar.txt”...? Is this even possible..? 这甚至可能..? I know that i can read a file from iside of foo.jar using 我知道我可以从foo.jar的iside读取文件

this.getClass().getClassLoader().getResourceAsStream("foo-bar.txt");

But I don't know how to do it from an external jar.. can someone help me? 但我不知道如何从外部罐子里做到这一点..有人能帮助我吗?

If the jar is in your classpath then getResourceAsStream will work, but note that it will find the first instance in your classpath. 如果jar在你的类路径中,则getResourceAsStream将起作用,但请注意它将在类路径中找到第一个实例。 If foo.jar and bar.jar both contain this file then it will return whichever jar is first in classpath. 如果foo.jar和bar.jar都包含这个文件,那么它将返回classpath中的第一个jar。

To read it from the jar use JarFile.getEntry and JarFile.getInputStream 要从jar中读取它,请使用JarFile.getEntryJarFile.getInputStream

Use jar url to open connection the example code 使用jar url打开连接示例代码

InputStream in = null;
String inputFile = "jar:file:/c:/path/to/my.jar!/myfile.txt";
if (inputFile.startsWith("jar:")){
  try {
    inputURL = new URL(inputFile);
    JarURLConnection conn = (JarURLConnection)inputURL.openConnection();
    in = conn.getInputStream();
  } catch (MalformedURLException e1) {
    System.err.println("Malformed input URL: "+inputURL);
    return;
  } catch (IOException e1) {
    System.err.println("IO error open connection");
    return;
  }
} 

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

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