gpt4 book ai didi

android - 使用 GZIPOutputStream 压缩字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:08:17 31 4
gpt4 key购买 nike

我想压缩我的字符串值。这些字符串值应与 .net 压缩字符串相同。

我写了Decompress 方法,当我向它发送一个.net 压缩字符串时,它工作正常。但是 Compress 方法无法正常工作。

public static String Decompress(String zipText) throws IOException {
int size = 0;
byte[] gzipBuff = Base64.decode(zipText);

ByteArrayInputStream memstream = new ByteArrayInputStream(gzipBuff, 4,
gzipBuff.length - 4);
GZIPInputStream gzin = new GZIPInputStream(memstream);

final int buffSize = 8192;
byte[] tempBuffer = new byte[buffSize];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((size = gzin.read(tempBuffer, 0, buffSize)) != -1) {
baos.write(tempBuffer, 0, size);
}
byte[] buffer = baos.toByteArray();
baos.close();

return new String(buffer, "UTF-8");
}
public static String Compress(String text) throws IOException {
byte[] gzipBuff = EncodingUtils.getBytes(text, "UTF-8");

ByteArrayOutputStream bs = new ByteArrayOutputStream();
GZIPOutputStream gzin = new GZIPOutputStream(bs);

gzin.write(gzipBuff);
gzin.finish();
bs.close();

byte[] buffer = bs.toByteArray();
gzin.close();

return Base64.encode(buffer);
}

For example when I send "BQAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyLmeVlW/w+GphA2BQAAAA==" to Decompress method It returns the string "Hello ”,但是当我向 Compress 方法发送 “Hello” 时,它会返回 “H4sIAAAAAAAAAAMtIzcnJBwCGphA2BQAAAA==”

Compress 方法有什么问题????

最佳答案

检查 Use Zip Stream and Base64 Encoder to Compress Large String Data

关于如何使用 GZIPOutputStream/GZIInputStream 和 Base64 编码器和解码器来压缩和解压缩大字符串数据,以便在 http 响应中将其作为文本传递。

public static String compressString(String srcTxt) throws IOException {
ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
GZIPOutputStream zos = new GZIPOutputStream(rstBao);
zos.write(srcTxt.getBytes());
IOUtils.closeQuietly(zos);

byte[] bytes = rstBao.toByteArray();
return Base64.encodeBase64String(bytes);
}

或者我们可以使用Use Zip Stream and Base64 Encoder to Compress Large String Data以避免将整个字符串加载到内存中。

public static String uncompressString(String zippedBase64Str) throws IOException {
String result = null;
byte[] bytes = Base64.decodeBase64(zippedBase64Str);
GZIPInputStream zi = null;
try {
zi = new GZIPInputStream(new ByteArrayInputStream(bytes));
result = IOUtils.toString(zi);
} finally {
IOUtils.closeQuietly(zi);
}
return result;
}

关于android - 使用 GZIPOutputStream 压缩字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6747454/

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