8

我想压缩一个InputStream使用ZipOutputStream然后InputStream从压缩ZipOutputStream而不将文件保存在磁盘上。那可能吗?

4

1 回答 1

29

我想到了:

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());
}
于 2013-11-27T09:56:36.990 回答