有人知道为什么这个创建压缩字符串的代码不起作用吗?Mac上的CLI无法打开结果文件:“不是gz格式的”。
请注意:我需要字符串,而不是文件。直接创建gzipped文件是可行的,在不压缩JSON的情况下编写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;
}编辑:雪兰教我的方法:
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。非常感谢!
发布于 2013-11-22 16:33:39
您正在通过一个具有字符编码和其他类似故障的String往返二进制数据。直接使用byte[]代替。
https://stackoverflow.com/questions/20149758
复制相似问题