簡體   English   中英

Java GZIPOutputStream:使用此方法損壞了gzip

[英]Java GZIPOutputStream: Corrupted gzip with this method

有人知道為什么這個代碼創建一個gzipped字符串不起作用? Mac上的CLI gzip無法打開生成的文件:“Not in gz format”。

請注意:我需要字符串,而不是文件。 直接創建gzip文件是有效的,編寫JSON也不會壓縮它。 此示例中的文件編寫僅用於測試目的。

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

編輯: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;
}

這導致了一個工作gzip壓縮的JSON。 非常感謝!

您通過String二進制數據進行往返運算,該String具有字符編碼和其他此類重整功能。 直接使用byte[]代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM