[英](de)compress base64 string
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.
谢谢。
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();
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. 您正在获取一些压缩数据,并试图将其解释为UTF-8字符串。 This is unsafe, and is resulting in the encoded string containing a bunch of "?"s instead of the intended data.
这是不安全的,并导致编码的字符串包含一串“?”而不是预期的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.