2011-07-19 41 views
4

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

我写了解压缩方法和当我发送一个.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 ==”解压方法它返回字符串“你好”,但是当我送“你好”压缩方法,它返回“H4sIAAAAAAAAAMtIzcnJBwCGphA2BQAAAA ==”

什么是压缩方法的问题????

回答

0

我与Java虚拟机试过我想的结果是一样的。 使用这条线在您的压缩方法的末尾:

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

在机器人抱歉构造函数字符串(字符串,字符串)是未定义 – breceivemail

+0

文档说说encodeToString()方法:[Base64.html](http://developer.android.com/reference/android/util /Base64.html#encode%28byte[],%20int%29)。我无法尝试,我无法在我的电脑上安装android。 – revo

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; 
} 
+0

请尝试读取这个http://stackoverflow.com/help/deleted-answers,以获得更多的理解如何** **不回答。即:“不能从根本上回答问题的答案”:**仅仅是一个链接到外部网站** –