Java:访问嵌入式jar文件中的文件

时间:2015-02-17 21:48:25

标签: java

我有一个名为“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);”中会抛出异常,说“文件名,目录名或卷标语法不正确”

任何人都可以帮助我吗?

由于

1 个答案:

答案 0 :(得分:1)

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