Consider the code example that put a single file test_file.pdf
into zip archive test.zip
and then read this archive:
import java.io.*;
A simple and elegant workaround is to write the ZipEntry
to a temporary ZipOutputStream
first. This is what the updateEntry
method of the following code does. When the method has been called, the ZipEntry
knows the size, compressed size and CRC, without having to calculate them explicitly. When it is written to the target ZipOutputStream
, it will correctly write the values.
Original answer:
dirty but fast
public static void main(String[] args) throws IOException
{
FileInputStream fis = new FileInputStream( "source.txt" );
FileOutputStream fos = new FileOutputStream( "result.zip" );
ZipOutputStream zos = new ZipOutputStream( fos );
byte[] buf = new byte[fis.available()];
fis.read(buf);
ZipEntry e = new ZipEntry( "source.txt" );
updateEntry(e, buf);
zos.putNextEntry(e);
zos.write(buf);
zos.closeEntry();
zos.close();
}
private static void updateEntry(ZipEntry entry, byte[] buffer) throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream( bos );
zos.putNextEntry(entry);
zos.write(buffer);
zos.closeEntry();
zos.close();
bos.close();
}