更新jar文件的内容

时间:2014-05-12 22:58:59

标签: java file jar

我正在尝试将文本文件添加到现有jar中。

这是它应该如何运作的:

  • JarFile A:运行时,会在JarFile B中添加一个文本文件。

  • JarFile B:运行时,它会从JarFile A添加的textfiel中读取一些配置选项。

以下是JarFileA为添加文件而执行的代码:

public static void updateZipFile(File zipFile, String targetPackage, File[] files) throws IOException {
    // get a temp file
    File tempFile = createTempFile(zipFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    tempFile.delete();

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException("Could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (File f : files) {
            if (f.getName().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(name));
            // Transfer bytes from the ZIP file to the output file
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }
    // Close the streams        
    zin.close();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(targetPackage + File.separator + file.getName()));
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Complete the ZIP file
    out.close();
    tempFile.delete();
}

这一切在Mac OS X上运行正常,但在Windows中它不起作用。它复制文件,但JarFileB无法读取这个新创建的文件。也许罐子腐败了?

非常感谢任何帮助。

感谢。

0 个答案:

没有答案