6

我有一个方法

      public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
        // a.) create gzip of inputStream
        final GZIPInputStream zipInputStream;
        try {
            zipInputStream = new GZIPInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
        }

我想将其转换inputStreamzipInputStream,这样做的方法是什么?

  • 上述方法不正确并抛出异常为“不是 Zip 格式”

将 Java Streams 转换为我真的很困惑,我没有让它们正确

4

2 回答 2

11

GZIPInputStream用于解压缩传入的InputStream. 要使用 GZIP 压缩传入InputStream,您基本上需要将其写入GZIPOutputStream.

InputStream如果您使用将ByteArrayOutputStreamgzip 压缩的内容写入 abyte[]并将ByteArrayInputStreamabyte[]转换为InputStream.

所以,基本上:

public void put(@Nonnull final InputStream inputStream, @Nonnull final String uniqueId) throws PersistenceException {
    final InputStream zipInputStream;
    try {
        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutput = new GZIPOutputStream(bytesOutput);

        try {
            byte[] buffer = new byte[10240];
            for (int length = 0; (length = inputStream.read(buffer)) != -1;) {
                gzipOutput.write(buffer, 0, length);
            }
        } finally {
            try { inputStream.close(); } catch (IOException ignore) {}
            try { gzipOutput.close(); } catch (IOException ignore) {}
        }

        zipInputStream = new ByteArrayInputStream(bytesOutput.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
        throw new PersistenceException("Persistence Service could not received input stream to persist for " + uniqueId);
    }

    // ...

如有必要,您ByteArrayOutputStream可以在ByteArrayInputStreamFileOuputStream.FileInputStreamFile#createTempFile()

于 2012-09-07T16:42:46.933 回答
5

GZIPInputStream用于读取gzip 编码的内容。

如果您的目标是获取常规输入流并将其压缩为 GZIP 格式,那么您需要将这些字节写入GZIPOutputStream

另请参阅相关问题的答案

于 2012-09-07T16:36:26.803 回答