Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping InputStream, returning InputStream (in memory, no file)

Tags:

java

zip

I am trying to do compress an InputStream and return an InputStream:

public InputStream compress (InputStream in){
  // Read "in" and write to ZipOutputStream
  // Convert ZipOutputStream into InputStream and return
}

I am compressing one file (so I could use GZIP) but will do more in future (so I opted for ZIP). In most of the places:

  • Compress an InputStream with gzip

  • How can I convert ZipInputStream to InputStream?

    They use toBytesArray() or getBytes() which do not exist (!) - ZipOutputStream

My problems are:

  1. How do I convert the ZipOutPutStream into InputStream if such methods don't exist?

  2. When creating the ZipOutPutStream() there is no default constructor. Should I create a new ZipOutputStrem(new OutputStream() ) ??

like image 633
user1156544 Avatar asked Jul 29 '13 15:07

user1156544


2 Answers

Something like that:

private InputStream compress(InputStream in, String entryName) throws IOException {
        final int BUFFER = 2048;
        byte buffer[] = new byte[BUFFER];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(out);
        zos.putNextEntry(new ZipEntry(entryName));
        int length;
        while ((length = in.read(buffer)) >= 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        zos.close();
        return new ByteArrayInputStream(out.toByteArray());
}
like image 188
soda Avatar answered Oct 18 '22 23:10

soda


  1. Solved it with a ByteArrayOutputStream which has a .toByteArray()
  2. Same here, passing the aforementioned element
like image 2
user1156544 Avatar answered Oct 19 '22 00:10

user1156544