【发布时间】:2016-12-26 12:29:37
【问题描述】:
我想在java中解压一个在python中被gzip压缩的字符串。
通常,我在 python 中对压缩字符串使用 base64 编码,然后在 java 中执行解压缩之前对该压缩字符串进行解码。这在使用 base64 编码时可以正常工作。
但是有没有办法在不使用base64编码的情况下解压java中的gzip压缩的字符串。
实际上,我想将压缩的二进制数据 http 发布到二进制数据解压缩的服务器。这里的压缩和http post在python中完成,服务器端是java。
我在 python 中尝试了没有 base64 编码的这段代码,并在 java 中使用缓冲读取器读取了该代码,然后使用 getBytes() 将读取的压缩字符串转换为 byte[],并提供给 GZIPInputStream 进行解压缩。但这会引发异常:
java.io.IOException: Not in GZIP format at
java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:154)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:75)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:85)
at GZipFile.gunzipIt(GZipFile.java:58)
at GZipFile.main(GZipFile.java:42)
请给我一个解决方案,在没有任何编码的情况下执行压缩和解压缩。有没有办法在python的http post中发送二进制数据?
这是python中的压缩代码:
import StringIO
import gzip
import base64
import os
m='hello'+'\r\n'+'world'
out = StringIO.StringIO()
with gzip.GzipFile(fileobj=out, mode="wb") as f:
f.write(m)
f=open('comp_dump','wb')
f.write(base64.b64encode(out.getvalue()))
f.close()
这是java中的解压代码:
//$Id$
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import javax.xml.bind.DatatypeConverter;
import java.util.Arrays;
public class GZipFile
{
public static String readCompressedData()throws Exception
{
String compressedStr ="";
String nextLine;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("comp_dump")));
try
{
while((nextLine=reader.readLine())!=null)
{
compressedStr += nextLine;
}
}
finally
{
reader.close();
}
return compressedStr;
}
public static void main( String[] args ) throws Exception
{
GZipFile gZip = new GZipFile();
byte[] contentInBytes = DatatypeConverter.parseBase64Binary(readCompressedData());
String decomp = gZip.gunzipIt(contentInBytes);
System.out.println(decomp);
}
/**
* GunZip it
*/
public static String gunzipIt(final byte[] compressed){
byte[] buffer = new byte[1024];
StringBuilder decomp = new StringBuilder() ;
try{
GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(compressed));
int len;
while ((len = gzis.read(buffer)) > 0) {
decomp.append(new String(buffer, 0, len));
}
gzis.close();
}catch(IOException ex){
ex.printStackTrace();
}
return decomp.toString();
}
}
【问题讨论】:
标签: java python base64 gzip compression