java (解)压缩base64字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13981965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(de)compress base64 string
提问by Jaros?aw Maciejewski
PHP code:
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
Below code return:
下面的代码返回:
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
I'm trying compress string in Java.
我正在尝试用 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
但是打印错误的字符串:eD8L
Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==
Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==
must be:
必须是:
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
How fix it? Thanks.
怎么修?谢谢。
回答by Akdeniz
Use Deflater
like this :
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();
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();
回答by duskwuff -inactive-
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.
您正在获取一些压缩数据并尝试将其解释为 UTF-8 字符串。这是不安全的,并导致编码字符串包含一堆“?”而不是预期的数据。