我正在使用以下代码来压缩然后解压缩字符串。但解压后我得到的字符串长度不同,解压后的字符串中也缺少一些字符。
压缩:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream zos = new GZIPOutputStream(baos);
zos.write(text.getBytes());
zos.finish();
zos.flush();
byte[] udpBuffer = baos.toByteArray();
System.out.println("Compressed length: " + udpBuffer.length);
解压:
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
BufferedReader br = new BufferedReader(new InputStreamReader(gis));
StringBuilder sb = new StringBuilder();
while (br.readLine()!= null) {
sb.append(br.readLine());
}
System.err.println(sb.toString());
文本原始长度:45627字节
文本压缩长度:3732字节
文本未压缩长度:20328字节(应等于原始长度)
我的原文是这样的:
<html>
<head>
<title></title>
</head>
<body>
<p><span class="preheader" style="display:none!important;mso-hide:all">Hey wazzup? </span></p>
<table align="center" border="0" cellpadding="0" cellspacing="0" width="640">
<tbody>
<tr>
<td align="center" height="30" style="font-size:11px;color:#333;font-family:Verdana,Geneva,sans-serif">
.
.
.
</tbody>
</body>
</html>
我的解压缩文本就像这样(看到开始标签丢失了,还有
<title> tag, similarly many tags and other parts are missing from my uncompressed text:
<head></head><p><span class="preheader" style="display:none!important;mso-hide:all">
.
.
.
谁能指出错误吗?或者这是预期的行为?
最佳答案
改变
while (br.readLine()!= null) {
sb.append(br.readLine());
}
至
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
此外,zos.flush() 应该在 zos.finish() 之前调用。
关于java - GZIP压缩与解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22920592/