Java:如何将InputStream转换为GZIPInputStream?

7

我有一个类似如下的方法:

      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);
        }

我想把inputStream转换成zipInputStream,有什么方法可以做到吗?

  • 上述方法是不正确的,会抛出异常,提示“不是Zip格式”

对我来说,将Java流进行转换确实很困惑,我经常无法正确处理它们


你为什么认为提供的 InputStream 返回 GZIP 内容?异常信息明确说明它不是。具体的功能要求是什么?为什么你需要以这种方式“转换”它? - BalusC
我需要将文档以压缩格式保存在Amazon S3上,以节省空间和减少费用,因此输入流是我正在尝试压缩并发送到S3的文档。 - daydreamer
2
啊,这样就说得通了。我已经发布了一个答案。在未来的问题中,请不要忘记清楚地说明具体的功能需求。尝试询问如何解决问题,而不是如何实现你认为是正确解决方案的解决方案。否则,该问题可能永远不会收到有效的答案,你将继续摸索。 - BalusC
2个回答

12

使用GZIPInputStream来对传入的InputStream进行解压缩操作。如果要使用GZIP对传入的InputStream进行压缩,则需要将其写入GZIPOutputStream中。

如果要将gzipped内容写入byte[]中,可以使用ByteArrayOutputStream,并使用ByteArrayInputStreambyte[]转换为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);
    }

    // ...

如果必要的话,您可以使用由File#createTempFile()创建的临时文件,将ByteArrayOutputStream/ByteArrayInputStream替换为FileOuputStream/FileInputStream,特别是在这些流可能包含大量数据且在并发使用时可能会超出计算机的可用内存。


5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接