2013-11-22 32 views
0

有人有一個想法,爲什麼這段代碼來創建一個gzipped字符串不工作? Mac上的CLI gzip無法打開結果文件:「不是gz格式」。Java GZIPOutputStream:用這種方法損壞gzip

請注意:我需要字符串,而不是文件。直接創建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。 非常感謝!

回答

2

您正在通過String將二進制數據往返,其中包含字符編碼和其他類似的變形。直接使用byte[]

+0

非常感謝。有任何,呃,例子:)或者,在哪些行應該使用byte []來代替? – user1840267

+0

@ user1840267到處都有'String'。具體來說,您應該從'gzippedString'方法中返回'byte []'(from'outputStream.toByteArray()')(並重命名它)。另外,不要不必要地使用十七個間接級別;你可以直接說'new FileWriter(this.jsonOutputPath +「/myfile.gz」)'。 – chrylis