[英]Java: Access a file in a embedded jar file
我有一個名為“ jar1.jar”的jar文件。 在內部,它具有另一個名為“ jar2.jar”的jar文件。
“ jar2.jar”的內容是:“ file.txt”。
jar1.jar
|
|-> jar2.jar
|
|-> file.txt
我想獲取“ file.txt”的內容。
我的代碼如下:
try{
String secondJarPath=Myclass.class.getResource("jar2.jar").getPath();
//An exception is thrown
JarFile secondJar = new JarFile(secondJarPath);
JarEntry entry =secondJar.getJarEntry("file.txt");
InputStream inputStream = entry.getInputStream(entry);
String content= IOUtils.toString(inputStream, Charset.forName("UTF-8"));
}
catch(IOException e){
}
但是,在“ JarFile secondJar = new JarFile(secondJarPath);”行中引發異常,說“文件名,目錄名或卷標簽語法不正確”
誰能幫我 ?
謝謝
try{
String firstJarPath = Junk.class.getResource("jar1.jar").getPath();
JarFile firstJar = new JarFile(firstJarPath);
JarEntry entry = firstJar.getJarEntry("jar2.jar");
InputStream isJar2 = firstJar.getInputStream(entry);
JarInputStream jisJar2 = new JarInputStream(isJar2);
JarEntry textFileEntry = jisJar2.getNextJarEntry();
if (textFileEntry.isDirectory()) {
jisJar2.close();
firstJar.close();
throw new Exception("didn't expect a directory");
} else {
int size = (int) textFileEntry.getSize();
if (size <= 0) {
System.out.print("ignore entry " + textFileEntry.getName() + " as size=" + size);
} else {
byte[] fileBytes = new byte[size];
IOUtils.read(jisJar2, fileBytes, 0, size);
ByteArrayInputStream ibs = new ByteArrayInputStream(fileBytes);
// ibs should be your file, so now do something with it....
}
}
jisJar2.close();
firstJar.close();
}
catch(IOException e){
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.