我尝试使用gunzip压缩字符串,对其进行编码,通过URL(GET请求)传递,然后对其进行解码和解压缩。我在压缩后进行Base64编码,因为根据我的理解,gunzip创建了一个字节流,并将其直接转换为字符串有点冒险。我似乎无法正常解压缩 - 我通常会得到一个EOF例外。我使用以下内容进行测试:
String compressed = myClass.compressStr(testStr);
String uncompressed = myClass.decompressStr(compressed);
Assert.assertEquals(testStr, uncompressed);
我用来驱动它的代码如下:
public static byte[] gzipCompress(byte[] bytes, int offset, int length)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
try
{
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
gzipOutputStream.write(bytes, offset, length);
gzipOutputStream.flush();
gzipOutputStream.close();
return baos.toByteArray();
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
public static byte[] gzipUncompress(byte[] src, int offset, int len)
{
ByteArrayInputStream bais = new ByteArrayInputStream(src, offset, len);
try
{
GZIPInputStream gzipInputStream = new GZIPInputStream(bais);
return ByteStreams.toByteArray(gzipInputStream);
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
public static String compressStr(String someStr) throws
UnsupportedEncodingException
{
final byte[] foo = Base64.decodeBase64(
someStr.getBytes("utf-8"));
final byte[] gunzippedBytes = CompressUtil.gzipCompress(
foo,
0,
foo.length - 1);
return Base64.encodeBase64String(gunzippedBytes);
}
public static String decompressStr(String compressedStr)
throws UnsupportedEncodingException
{
final byte[] compressedBytes = Base64.decodeBase64(
compressedStr);
final byte[] gunzippedBytes = CompressUtil.gzipUncompress(
compressedBytes,
0,
compressedBytes.length - 1);
return Base64.encodeBase64String(gunzippedBytes);
}
编码/解码到字符串的正确顺序是什么?我猜测我主要做了些什么。
答案 0 :(得分:0)
我尝试使用gunzip压缩字符串,对其进行编码,通过URL传递
那你为什么先在compressStr()方法中调用Base64.decodeBase64()? :)