(de)compress base64 string

懵懂的女人 提交于 2019-12-22 13:52:19

问题


PHP code:

$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

Below code return:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

I'm trying compress string in 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);      

But print wrong string: eD8L

Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==

must be:

C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA

How fix it? Thanks.


回答1:


Use Deflater like this :

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();

To decompress what is compressed:

    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
    Inflater decompresser = new Inflater(true);
    InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream2, decompresser);
    inflaterOutputStream.write(output);
    inflaterOutputStream.close();
    byte[] output2 = stream2.toByteArray();



回答2:


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

You are taking some compressed data and trying to interpret it as a UTF-8 string. This is unsafe, and is resulting in the encoded string containing a bunch of "?"s instead of the intended data.



来源:https://stackoverflow.com/questions/13981965/decompress-base64-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!