如何将文件添加到运行jar

时间:2016-11-09 01:10:33

标签: java file jar zip

这是我的代码,我正在寻找一种方法来将文件添加到正在运行的jar中。提前致谢。目前发生的错误是"无效的条目大小(预期62但得到0字节)。 62字节是我的MANIFEST文件的大小,它被写入。我不确定这与任何事情有什么关系。

        JarFile replace = new JarFile("newgame.jar");
        JarInputStream jis = null;
        JarOutputStream jos = new JarOutputStream(new FileOutputStream(
                Launcher.class.getProtectionDomain().getCodeSource().getLocation().getPath()));
        for (Enumeration<JarEntry> list = replace.entries(); list.hasMoreElements();) {
            JarEntry nextEntry = list.nextElement();
            if (!nextEntry.getName().equals("Launcher.class")) {
                jos.putNextEntry(nextEntry);
                jis = new JarInputStream(replace.getInputStream(nextEntry));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] byteBuff = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = jis.read(byteBuff)) != -1)
                    out.write(byteBuff, 0, bytesRead);
                jos.write(out.toByteArray());
                out.close();
                jis.close();
            }
        }
        replace.close();
        jos.close();
        new File("newgame.jar").delete();

1 个答案:

答案 0 :(得分:0)

已修复

        JarFile replace = new JarFile("newgame.jar");
        InputStream is = null;
        JarOutputStream jos = new JarOutputStream(new FileOutputStream(
                Launcher.class.getProtectionDomain().getCodeSource().getLocation().getPath()));
        for (Enumeration<JarEntry> list = replace.entries(); list.hasMoreElements();) {
            JarEntry nextEntry = list.nextElement();
            jos.putNextEntry(nextEntry);
            is = replace.getInputStream(nextEntry);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] byteBuff = new byte[(int) nextEntry.getSize()];
            int bytesRead = 0;
            while ((bytesRead = is.read(byteBuff, 0, byteBuff.length)) != -1)
                out.write(byteBuff, 0, bytesRead);
            jos.write(out.toByteArray());
            out.close();
            is.close();
        }
        replace.close();
        jos.close();
        new File("newgame.jar").delete();

我将JarInputStreams转换为InputStreams,并且出于某种原因,这有效。