Nat*_* F. 2 java jar file external
我正在尝试使用java从外部jar中读取文件.例如,我有两个jar文件.一个是"foo.jar",另一个是"bar.jar"."bar.jar"里面是文件"foo-bar.txt".如何使用"foo.jar"中的代码从"bar.jar"内部读取文件"foo-bar.txt"...?这甚至可能..?我知道我可以从foo.jar的iside读取文件
this.getClass().getClassLoader().getResourceAsStream("foo-bar.txt");
Run Code Online (Sandbox Code Playgroud)
但我不知道如何从外部罐子里做到这一点..有人能帮助我吗?
使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果jar在你的类路径中然后getResourceAsStream将工作,但请注意它将在类路径中找到第一个实例.如果foo.jar和bar.jar都包含这个文件,那么它将返回classpath中的第一个jar.
要从jar中读取它使用JarFile.getEntry和JarFile.getInputStream
| 归档时间: |
|
| 查看次数: |
7565 次 |
| 最近记录: |