【问题标题】:How to add files to running jar如何将文件添加到运行的jar
【发布时间】:2017-03-22 18:58:24
【问题描述】:

这是我的代码,我正在寻找一种将文件添加到正在运行的 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();

【问题讨论】:

  • 为什么要这样做?这可能是XY Problem。您的代码中的哪个语句给了您错误?
  • @JimGarrison jos.putNextEntry(nextEntry);给了我错误。

标签: java file jar zip


【解决方案1】:

固定
        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 并且由于某种原因这有效。

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多