简体   繁体   English

Java GZIPOutputStream:使用此方法损坏了gzip

[英]Java GZIPOutputStream: Corrupted gzip with this method

does someone have an idea why this code to create a gzipped string is not working? 有人知道为什么这个代码创建一个gzipped字符串不起作用? CLI gzip on a Mac can't open the resulting file: "Not in gz format". Mac上的CLI gzip无法打开生成的文件:“Not in gz format”。

Please note: I need the string, not the file. 请注意:我需要字符串,而不是文件。 Creating the gzipped file directly works, so does writing the JSON without zipping it. 直接创建gzip文件是有效的,编写JSON也不会压缩它。 The file writing in this example is just for testing purposes. 此示例中的文件编写仅用于测试目的。

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

EDIT: chrylis showed me the way: 编辑:chrylis给我指路:

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 results in a working gzipped JSON. 这导致了一个工作gzip压缩的JSON。 Thanks a lot! 非常感谢!

You're round-tripping binary data through a String , which has a character encoding and other such mangling. 您通过String二进制数据进行往返运算,该String具有字符编码和其他此类重整功能。 Use the byte[] directly instead. 直接使用byte[]代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM