我遇到了一个问题,但无法解决它或找到有用的答案。
我有一段压缩字节数组的代码:
try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
final GZIPOutputStream gzip = new GZIPOutputStream(byteArrayOutputStream);
gzip.write(response.getBytes());
gzip.close();
response = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Problem in compression", e);
}
它工作得很好,并且生成的压缩字节数组保存在数据库中。
我有另一段代码,它将获取数据库中压缩的字节数组并将其解压缩:
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream, BUFFER_SIZE);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gzipInputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, bytesRead);
}
gzipInputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Problem in decompression", e);
}
解压缩对于“大”字节数组(大于 32 字节)非常有效,但我有一个 20 字节的压缩数组,但我无法解压缩它。
它永远不会进入 while,因为读取总是返回 -1,所以什么也没有读取。
我尝试更改缓冲区大小等...但没有任何效果。
我做错了什么?
提前谢谢您!
这本质上是你的代码(尽管zip输入流应该位于try-with-resources块中),你可以运行它:
import java.util.*;
import java.util.zip.*;
import java.io.*;
public class Unzip {
public static void main(String[] args) throws Exception {
String s = "H4sIAAAAAAAAA3WRQW+CQBCF7/6K0dOSUNKeiYeaYMNJo+nFxjQrTHQTYMkwhNLG/95lESSIe9jDmzffm51lqkGsasZ3IllvSs5L3jOhTOE0qS4hwwomO4TjwwzM6athNoEbiiPaoCQineaERYGx48Cf5X4cwu2w+/yr8kfayCWmgl1Yfa7Xwe57Hx4Cx7f0xvd1hFiyvJGsMjAeW6PK2JaKHcrYn1mtuqgEQYheN4jReJ65YtHgzYPmS3h5697VpT9s1KtIMdoeF17de+pt5GsbPg6KEl2g+Y22SsglZU8CWPfLbxquEEmOLiDCTfATYc5KZ4DdnIk+e0ikSSy2pE8JpmYXEGP3Vca8cI3dcP4BN4CC8VgCAAA=";
final int BUFFER_SIZE = 32;
byte[] compressed = Base64.getDecoder().decode(s);
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressed)) {
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream, BUFFER_SIZE);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gzipInputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, bytesRead);
}
gzipInputStream.close();
System.out.println(new String(byteArrayOutputStream.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}
}
}