0

does someone have an idea why this code to create a gzipped string is not working? CLI gzip on a Mac can't open the resulting file: "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. 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:

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. Thanks a lot!

user1840267
  • 408
  • 1
  • 5
  • 18

1 Answers1

2

You're round-tripping binary data through a String, which has a character encoding and other such mangling. Use the byte[] directly instead.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Thanks a lot. Got any, uh, examples :) Or, in which lines should I use byte[] instead? – user1840267 Nov 22 '13 at 17:13
  • @user1840267 Everywhere you have `String`. Specifically, you should return `byte[]` (from `outputStream.toByteArray()`) from your `gzippedString` method (and rename it). Also, don't use seventeen levels of indirection unnecessarily; you can directly say `new FileWriter(this.jsonOutputPath + "/myfile.gz")`. – chrylis -cautiouslyoptimistic- Nov 22 '13 at 17:16