gpt4 book ai didi

Java:创建 GZIPInputStream 时出错:不是 GZIP 格式

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:23 27 4
gpt4 key购买 nike

我正在尝试使用以下 Java 代码来压缩和解压缩字符串。但是从新的 ByteArrayInputStream 对象创建新的 GZipInputStream 对象的行抛出“java.util.zip.ZipException:不是 GZIP 格式”异常。有谁知道如何解决这个问题?

        String orig = ".............";

// compress it
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
OutputStream outStream = new GZIPOutputStream(baostream);
outStream.write(orig.getBytes());
outStream.close();
String compressedStr = baostream.toString();

// uncompress it
InputStream inStream = new GZIPInputStream(new ByteArrayInputStream(compressedStr.getBytes()));
ByteArrayOutputStream baoStream2 = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int len;
while((len = inStream.read(buffer))>0)
baoStream2.write(buffer, 0, len);
String uncompressedStr = baoStream2.toString();

最佳答案

混合 Stringbyte[];那永远不合适。并且只适用于具有相同编码的相同操作系统。并非每个 byte[] 都可以转换为 String,并且转换回来可以得到其他字节。

compressedBytes 不需要代表字符串。

getBytesnew String 中显式设置编码。

    String orig = ".............";

// Compress it
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
OutputStream outStream = new GZIPOutputStream(baostream);
outStream.write(orig.getBytes("UTF-8"));
outStream.close();
byte[] compressedBytes = baostream.toByteArray(); // toString not always possible

// Uncompress it
InputStream inStream = new GZIPInputStream(
new ByteArrayInputStream(compressedBytes));
ByteArrayOutputStream baoStream2 = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int len;
while ((len = inStream.read(buffer)) > 0) {
baoStream2.write(buffer, 0, len);
}
String uncompressedStr = baoStream2.toString("UTF-8");

System.out.println("orig: " + orig);
System.out.println("unc: " + uncompressedStr);

关于Java:创建 GZIPInputStream 时出错:不是 GZIP 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14466840/

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