首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java:如何将InputStream转换为GZIPInputStream?

Java:如何将InputStream转换为GZIPInputStream?
EN

Stack Overflow用户
提问于 2012-09-07 16:32:26
回答 2查看 8.9K关注 0票数 6

我有一种方法

代码语言:javascript
运行
复制
      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流转换给我是非常令人困惑的,而且我没有纠正它们

EN

回答 2

Stack Overflow用户

发布于 2012-09-07 16:42:46

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

如果使用InputStream将gzipped内容写入byte[],使用ByteArrayInputStreambyte[]转换为InputStream,则可以从中获得一个新的byte[]

所以,基本上:

代码语言:javascript
运行
复制
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/ByteArrayInputStream替换为由File#createTempFile()创建的临时文件上的FileOuputStream/FileInputStream,特别是如果这些流可以包含大型数据,当并发使用时可能会溢出机器的可用内存。

票数 11
EN

Stack Overflow用户

发布于 2012-09-07 16:36:26

GZIPInputStream用于读取gzip编码内容。

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

另见这是对相关问题的回答

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12322073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档