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

4

2 回答 2

10

像这样的东西:

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());
}
于 2013-08-08T11:07:44.230 回答
2
  1. 使用具有 .toByteArray() 的 ByteArrayOutputStream 解决它
  2. 同样在这里,传递上述元素
于 2013-07-30T12:32:42.883 回答