如何在Android中压缩字符串



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

这就是我从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

,但我无法理解哪种方法将为我提供可以发送到服务的压缩输出。

我使用的数据是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();
    }

缩水器的文档表明输出被放入缓冲区output

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
 }

您需要编码,压缩,解压缩,解码

的所有代码

最新更新