我想在java中解压缩一个字符串,它在Python中被gzip压缩。
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)
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();
}
}
不是每个byte[]都可以转换成字符串,转换回来可能会给出其他字节。
请在压缩时明确定义编码,在解压缩时也这样做。否则您的OS
、JVM
等...会为你做的。很可能会把事情搞砸。
例如:在我的Linux机器上:
import sys
print sys.getdefaultencoding()
>> ascii
爪哇
System.out.println(Charset.defaultCharset());
>> UTF-8
相关解答:https://stackoverflow.com/a/14467099/3014866
问题内容: 我正在使用php的功能来执行HTTP请求。为了节省带宽,我决定使用添加标题。 显然,输出一个gzip编码的字符串,所以我用来解码该编码的字符串,但是将作为参数传递的数据出错。 我知道还有另一个功能可以解压缩压缩后的数据,但是它不包含在我的PHP版本中(也许仅在SVN上可用)。 我知道cUrl可以即时解码gzip流(没有任何问题),但是有人建议我使用它而不是cUrl。 您是否知道以其他方
我想在JavaScript中做解压缩图像。我已经用C#使用gzip压缩了图像。如何在JavaScript中解压缩gzipped数据? C#代码
找到这个:https://stackoverflow.com/a/11373078/530599-很好,但是 怎么样
使用的字符串: string='hello'+'\r\n'+'world' Java中的预期输出: out.getValue() f.write(Base64.b64Encode(Out.getValue())) F.Close() ByteArrayInputStream(压缩)); InputStreamReader(gis,“UTF-8”));
问题内容: 我有一个内存和磁盘受限的环境,我需要解压缩以字符串为基础的块(通过xmlrpc二进制传输)发送给我的gzip文件的内容。但是,使用zlib.decompress()或zlib.decompressobj()/ decompress()都可以在gzip标头上使用barf。我已经尝试过偏移gzip标头(在此处记录),但是仍然没有避免使用barf。gzip库本身似乎仅支持从文件解压缩。 以下