使用GZIPOutputStream压缩字符串

时间:2011-07-19 12:52:12

标签: android string compression gzip gzipoutputstream

我想压缩我的字符串值。这些字符串值应与.net压缩字符串相同。

我写了解压缩方法,当我发送一个.net压缩字符串时,它可以正常工作。但压缩方法无法正常工作。

public static String Decompress(String zipText) throws IOException {
    int size = 0;
    byte[] gzipBuff = Base64.decode(zipText);

    ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff, 4,
            gzipBuff.length - 4);
    GZIPInputStream gzin = new GZIPInputStream(memstream);

    final int buffSize = 8192;
    byte[] tempBuffer = new byte[buffSize];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((size = gzin.read(tempBuffer, 0, buffSize)) != -1) {
        baos.write(tempBuffer, 0, size);
    }
    byte[] buffer = baos.toByteArray();
    baos.close();

    return new String(buffer, "UTF-8");
}

-

public static String Compress(String text) throws IOException {

    byte[] gzipBuff = EncodingUtils.getBytes(text, "UTF-8");

    ByteArrayOutputStream bs = new ByteArrayOutputStream();

    GZIPOutputStream gzin = new GZIPOutputStream(bs);

    gzin.write(gzipBuff);

    gzin.finish();
    bs.close();

    byte[] buffer = bs.toByteArray();

    gzin.close();

    return Base64.encode(buffer);
}

例如当我发送的 “BQAAAB + LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee ++ 997o7nU4n99 // P1xmZAFs9s5K2smeIYCqyB8 / fnwfPyLmeVlW / W + GphA2BQAAAA ==”解压方法,它返回字符串“Hello “,但当我发送”Hello“压缩方法时,它返回”H4sIAAAAAAAAAMtIzcnJBwCGphA2BQAAAA ==“

压缩方法????

有什么问题

2 个答案:

答案 0 :(得分:3)

检查Use Zip Stream and Base64 Encoder to Compress Large String Data

关于如何使用GZIPOutputStream / GZIInputStream和Base64编码器和解码器来压缩和解压缩大字符串数据,因此它可以作为http响应中的文本传递。

public static String compressString(String srcTxt) throws IOException {
  ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
  GZIPOutputStream zos = new GZIPOutputStream(rstBao);
  zos.write(srcTxt.getBytes());
  IOUtils.closeQuietly(zos);

  byte[] bytes = rstBao.toByteArray();
  return Base64.encodeBase64String(bytes);
}

或者我们可以使用Use Zip Stream and Base64 Encoder to Compress Large String Data来避免将整个字符串加载到内存中。

public static String uncompressString(String zippedBase64Str) throws IOException {
  String result = null;
  byte[] bytes = Base64.decodeBase64(zippedBase64Str);
  GZIPInputStream zi = null;
  try {
    zi = new GZIPInputStream(new ByteArrayInputStream(bytes));
    result = IOUtils.toString(zi);
  } finally {
    IOUtils.closeQuietly(zi);
  }
    return result;
}

答案 1 :(得分:0)

我试过java vm我想结果是一样的。 在Compress方法结束时使用此行:

return new String(base64.encode(buffer), "UTF-8");