4

PHP代码:

$txt="John has cat and dog."; //plain text
$txt=base64_encode($txt); //base64 encode
$txt=gzdeflate($txt,9); //best compress
$txt=base64_encode($txt); //base64 encode
print_r($txt); //print it

以下代码返回:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

我正在尝试用 Java 压缩字符串。

        // Encode a String into bytes
     String inputString = "John has cat and dog.";
     inputString=Base64.encode(inputString);

     byte[] input = inputString.getBytes("UTF-8");

     // Compress the bytes
     byte[] output = new byte[100];
     Deflater compresser = new Deflater();
    //compresser.setLevel(Deflater.BEST_COMPRESSION);
     compresser.setInput(input);
     compresser.finish();
     int compressedDataLength = compresser.deflate(output);     
     String outputString = new String(output, 0, compressedDataLength,"UTF-8");     
     outputString=Base64.encode(outputString);  
     System.out.println(outputString);      

但是打印错误的字符串:eD8L

Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==

一定是:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

怎么修?谢谢。

4

2 回答 2

9

像这样使用Deflater

ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compresser);
deflaterOutputStream.write(input);
deflaterOutputStream.close();
byte[] output = stream.toByteArray();

要解压缩压缩的内容:

    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(true);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream2, decompresser);
    inflaterOutputStream.write(output);
    inflaterOutputStream.close();
    byte[] output2 = stream2.toByteArray();
于 2012-12-21T02:17:07.657 回答
0
 String outputString = new String(output, 0, compressedDataLength,"UTF-8");     

您正在获取一些压缩数据并尝试将其解释为 UTF-8 字符串。这是不安全的,并导致编码字符串包含一堆“?”而不是预期的数据。

于 2012-12-21T01:34:00.587 回答