(de)压缩base64字符串

时间:2012-12-20 23:07:54

标签: java php base64

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 /人民币/ TjJKLgUAPygJTA ==

必须是:

  

C861zE / KdMqPjPBNjzRyM / B0dyuNcnbKTjJKLgUA

如何解决?感谢。

2 个答案:

答案 0 :(得分:6)

像这样使用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();

答案 1 :(得分:0)

 String outputString = new String(output, 0, compressedDataLength,"UTF-8");     

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