Java 将文件添加到现有Zip存档中

Java 将文件添加到现有Zip存档中,java,apache-commons,Java,Apache Commons,所以我遵循了这里的代码块:,这里说的是简单地做一个ZipArchiveEntry,然后插入数据。正如我下面的代码所示 public void insertFile(File apkFile, File insert, String method) throws AndrolibException { ZipArchiveOutputStream out = null; ZipArchiveEntry entry; try {

所以我遵循了这里的代码块:,这里说的是简单地做一个ZipArchiveEntry,然后插入数据。正如我下面的代码所示

    public void insertFile(File apkFile, File insert, String method)
    throws AndrolibException {
        ZipArchiveOutputStream out = null;
        ZipArchiveEntry entry;

        try {
            byte[] data = Files.toByteArray(insert);
            out = new ZipArchiveOutputStream(new FileOutputStream(apkFile, true));
            out.setMethod(Integer.parseInt(method));
            CRC32 crc = new CRC32();
            crc.update(data);
            entry = new ZipArchiveEntry(insert.getName());
            entry.setSize(data.length);
            entry.setTime(insert.lastModified());
            entry.setCrc(crc.getValue());
            out.putArchiveEntry(entry);
            out.write(data);
            out.closeArchiveEntry();
            out.close();
        } catch (FileNotFoundException ex) {
            throw new AndrolibException(ex);
        } catch (IOException ex) {
            throw new AndrolibException(ex);
        }
}
基本上,它传递的文件(apkFile)将接受“insert”文件,另一个参数指示该文件的压缩方法。运行此代码块会导致0个错误,但ZIP文件中只有“新”文件。它删除所有以前的文件,然后插入新文件


在commons压缩之前,我必须将整个Zip复制到一个临时文件中,进行更改,然后将最终的Zip文件复制回来。我认为这个库解决了这个问题。

当您处理完流(即
out.close()
)时,您总是希望
close()
,最好是在finally块中。

作为一种替代方法:我编写了一些实用方法,使用NIO.2文件API将文件和目录复制到Zip文件中(该库是开源的):

马文:

<dependency>  
    <groupId>org.softsmithy.lib</groupId>  
    <artifactId>softsmithy-lib-core</artifactId>  
    <version>0.3</version>  
</dependency>  

org.softsmithy.lib


API:

你是否关闭了
文件
?啊,忘记了一些简单的事情:/now添加关闭文件只会覆盖整个Zip存档文件到我插入的任何文件。你应该编辑问题并添加它。另外,如果你所做的只是将其转换为
int
,为什么不使用
int
参数呢参数已经存在?传入参数有时以字符串/int的形式出现。为了安全起见,我只是将其作为字符串并作为int进行解析。您找到解决方案了吗?我的代码要么覆盖现有的ZIP
new FileOutputStream(ZIP)
,要么什么都不做
new FileOutputStream(ZIP,true)
。或者使用Java SE 7:最好是在“使用资源进行尝试”块中。