我编写了一个简单的 Java 代码片段,它接受一个字符串,将其转换为 byte[],然后使用 Gzip 对其进行压缩。然后它解压缩结果以取回 byte[],它现在包含一个额外的垃圾值字节。为什么这里有一个垃圾值字节??
公共静态 void main(String[] args) 抛出异常 {
String testString = "Sample String here";
byte[] originalBytes = testString.getBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(baos);
gzos.write(originalBytes);
gzos.close();
byte[] compressedBytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(compressedBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
ByteArrayOutputStream dbaos = new ByteArrayOutputStream();
while(gzis.available() > 0) {
dbaos.write(gzis.read());
}
byte[] decompressedBytes = dbaos.toByteArray();
String decompressedString = new String(decompressedBytes);
System.out.println(">>" + decompressedString + "<<");
System.out.println("Size of bytes before: " + originalBytes.length);
System.out.println("Size of bytes after: " + decompressedBytes.length);
}
输出:
>>Sample String here�<<
Size of bytes before: 18
Size of bytes after: 19
有人能告诉我为什么会有一个垃圾值字节吗?如何在不更改上面代码设置的情况下摆脱它?