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
Run Code Online (Sandbox Code Playgroud)
下面代码返回:
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);
Run Code Online (Sandbox Code Playgroud)
但打印错误的字符串:eD8L
Pz9PP3Q/Pz9NPzRyMz90dys/CNY/TjJKLgUAPygJTA ==
一定是:
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
如何解决?谢谢.
使用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();
Run Code Online (Sandbox Code Playgroud)
要解压缩压缩的内容:
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
Inflater decompresser = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream2, decompresser);
inflaterOutputStream.write(output);
inflaterOutputStream.close();
byte[] output2 = stream2.toByteArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10271 次 |
| 最近记录: |