【问题标题】:How to compress a String in Android如何在 Android 中压缩字符串
【发布时间】:2017-09-29 20:13:44
【问题描述】:

我正在尝试压缩一个大字符串对象。这是我尝试过的,但我无法理解如何获取压缩数据,以及如何定义不同类型的压缩工具。

这是我从 Android 文档中得到的。

        byte[] input = jsonArray.getBytes("UTF-8");
        byte[] output = new byte[100];

        Deflater compresser = new Deflater();
        compresser.setInput(input);
        compresser.finish();
        int compressedDataLength = compresser.deflate(output);
        compresser.end();

compresser.deflate(output) 给了我一个int 号码,100

但我无法理解哪种方法会给我可以发送到服务的压缩输出。

【问题讨论】:

  • 可能是output 是输出? :) 为什么需要方法?
  • 它有数据,但在示例中我没有在任何地方设置它
  • 您在此处设置:compresser.deflate(output)

标签: android performance android-layout android-fragments deflate


【解决方案1】:

我用来压缩数据的算法是 Huffman。您可以通过简单的搜索找到它。但在你的情况下,它可能对你有帮助:

public static byte[] compress(String data) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    gzip.write(data.getBytes());
    gzip.close();
    byte[] compressed = bos.toByteArray();
    bos.close();
    return compressed;
}

要解压,你可以使用:

public static String decompress(byte[] compressed) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
        GZIPInputStream gis = new GZIPInputStream(bis);
        BufferedReader br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        gis.close();
        bis.close();
        return sb.toString();
    }

【讨论】:

  • 解压呢?
  • 我刚刚编辑了我的答案。感谢您的提醒;)
【解决方案2】:

Deflator 的文档显示输出被放入缓冲区 output

【讨论】:

    【解决方案3】:
    try {
         // Encode a String into bytes
         String inputString = "blahblahblah";
         byte[] input = inputString.getBytes("UTF-8");
    
         // Compress the bytes
         byte[] output = new byte[100];
         Deflater compresser = new Deflater();
         compresser.setInput(input);
         compresser.finish();
         int compressedDataLength = compresser.deflate(output);
         compresser.end();
    
         // Decompress the bytes
         Inflater decompresser = new Inflater();
         decompresser.setInput(output, 0, compressedDataLength);
         byte[] result = new byte[100];
         int resultLength = decompresser.inflate(result);
         decompresser.end();
    
         // Decode the bytes into a String
         String outputString = new String(result, 0, resultLength, "UTF-8");
     } catch(java.io.UnsupportedEncodingException ex) {
         // handle
     } catch (java.util.zip.DataFormatException ex) {
         // handle
     }
    

    您需要编码、压缩、解压缩、解码的所有代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      • 2015-01-05
      • 2011-04-08
      • 1970-01-01
      • 2012-10-10
      相关资源
      最近更新 更多