首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java GZIPOutputStream:使用此方法损坏的gzip

Java GZIPOutputStream:使用此方法损坏的gzip
EN

Stack Overflow用户
提问于 2013-11-22 16:28:46
回答 1查看 1.5K关注 0票数 0

有人知道为什么这个创建压缩字符串的代码不起作用吗?Mac上的CLI无法打开结果文件:“不是gz格式的”。

请注意:我需要字符串,而不是文件。直接创建gzipped文件是可行的,在不压缩JSON的情况下编写JSON也是如此。本例中的文件编写只是为了测试目的。

代码语言:javascript
复制
public someMethod {
            String gzippedString = this.gzippedString(finalJSONObject.toJSONString());
            OutputStream outputStream = new FileOutputStream(new File(this.jsonOutputPath + "/myfile.gz"));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.append(gzippedString);
            writer.close();
        }

private String gzippedString(String inputString) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
        gzipOutputStream.write(inputString.getBytes());
        gzipOutputStream.close();
        outputStream.close();
        String gzippedString = outputStream.toString();
        return gzippedString;
    }

编辑:雪兰教我的方法:

代码语言:javascript
复制
public void someMethod() {
        byte[] byteArray = this.gzippedByteArray(finalJSONObject.toJSONString());
        FileOutputStream out = new FileOutputStream(this.jsonOutputPath + "/myfile.gz");
        out.write(byteArray);
        out.close();
}


private byte[] gzippedByteArray(String inputString) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
        gzipOutputStream.write(inputString.getBytes());
        gzipOutputStream.close();
        outputStream.close();
        byte[] gzippedByteArray = outputStream.toByteArray();
        return gzippedByteArray;
}

这将产生一个工作的This。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-22 16:33:39

您正在通过一个具有字符编码和其他类似故障的String往返二进制数据。直接使用byte[]代替。

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

https://stackoverflow.com/questions/20149758

复制
相关文章

相似问题

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