10

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:

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() ) ??

Community
  • 1
  • 1
user1156544
  • 1,725
  • 2
  • 25
  • 51

2 Answers2

11

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());
}
Zefiro
  • 2,821
  • 2
  • 20
  • 21
soda
  • 111
  • 3
  • 3
    Just a small note: In the while statement, you should check if in.read(buffer) >= 0. Because if the inputstream isn't ready, it might return 0 bytes read, but the end isn't reached, the stream might be ready later. So it shouldn't be considered finished until it returns -1 – Einar Bjerve Jun 03 '16 at 13:29
  • 1
    Is it possible to do the same using GZIP? – Dinesh Nov 29 '19 at 10:21
2
  1. Solved it with a ByteArrayOutputStream which has a .toByteArray()
  2. Same here, passing the aforementioned element
user1156544
  • 1,725
  • 2
  • 25
  • 51