Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ZipOutputStream to ByteArrayInputStream

I want to compress an InputStream using ZipOutputStream and then get the InputStream from compressed ZipOutputStream without saving file on disc. Is that possible?

like image 800
yasser Avatar asked Nov 26 '13 15:11

yasser


1 Answers

I figured it out:

public InputStream getCompressed(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    ZipOutputStream zos = new ZipOutputStream(bos);
    zos.putNextEntry(new ZipEntry(""));

    int count;
    byte data[] = new byte[2048];
    BufferedInputStream entryStream = new BufferedInputStream(is, 2048);
    while ((count = entryStream.read(data, 0, 2048)) != -1) {
        zos.write( data, 0, count );
    }
    entryStream.close();

    zos.closeEntry();
    zos.close();

    return new ByteArrayInputStream(bos.toByteArray());
}
like image 61
yasser Avatar answered Oct 05 '22 06:10

yasser