Copy a ZipEntry into another zip file

Wang Weijun weijun.wang at oracle.com
Mon Dec 15 03:43:23 UTC 2014


Hi Sherman

The jarsigner tool contains these 2 methods to copy a ZipEntry into the signer jar:

private void writeEntry(ZipFile zf, ZipOutputStream os, ZipEntry ze)
throws IOException
{
    ZipEntry ze2 = new ZipEntry(ze.getName());
    ze2.setMethod(ze.getMethod());
    ze2.setTime(ze.getTime());
    ze2.setComment(ze.getComment());
    ze2.setExtra(ze.getExtra());
    if (ze.getMethod() == ZipEntry.STORED) {
        ze2.setSize(ze.getSize());
        ze2.setCrc(ze.getCrc());
    }
    os.putNextEntry(ze2);
    writeBytes(zf, ze, os);
}

/**
 * Writes all the bytes for a given entry to the specified output stream.
 */
private synchronized void writeBytes
    (ZipFile zf, ZipEntry ze, ZipOutputStream os) throws IOException {
    int n;

    InputStream is = null;
    try {
        is = zf.getInputStream(ze);
        long left = ze.getSize();

        while((left > 0) && (n = is.read(buffer, 0, buffer.length)) != -1) {
            os.write(buffer, 0, n);
            left -= n;
        }
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

Several questions:

1. Why cannot I just call os.putNextEntry(ze) or at least os.putNextEntry(new ZipEntry(ze))? Maybe some fields (say, compressed size) should not be copied over? If ze2 must be this way, shall I also copy the flag field?

2. In writeBytes(), why does the getSize() return value need to be used? Shouldn't we just transfer all bytes from is to os?

Thanks
Max




More information about the core-libs-dev mailing list