gpt4 book ai didi

java - (解)压缩 base64 字符串

转载 作者:行者123 更新时间:2023-11-30 05:50:31 27 4
gpt4 key购买 nike

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

解压缩压缩的内容:

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

关于java - (解)压缩 base64 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13981965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com