我正在尝试读取 gzip 文件的内容并从中创建一个文件。我遇到了一个我无法解决的问题。任何建议的想法都表示赞赏。谢谢。
private static String unzip(String gzipFile, String location){
try {
FileInputStream in = new FileInputStream(gzipFile);
FileOutputStream out = new FileOutputStream(location);
GZIPInputStream gzip = new GZIPInputStream(in);
byte[] b = new byte[1024];
int len;
while((len = gzip.read(b)) != -1){
out.write(buffer, 0, len);
}
out.close();
in.close();
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
最佳答案
使用 Resource Blocks 将使您的生活变得更加轻松。以确保您的文件正确关闭。例如:
private static String unzip(String gzipFile, String location){
try (
FileInputStream in = new FileInputStream(gzipFile);
GZIPInputStream gzip = new GZIPInputStream(in);
FileOutputStream out = new FileOutputStream(location))
{
byte[] b = new byte[4096];
int len;
while((len = gzip.read(b)) >= 0){
out.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
您还应该确保您拥有有效的 .zip 文件(当然!)并且您的输入和输出文件名不同。
“缓冲区”是怎么回事?我假设(GPI 也是如此)您可能指的是“b”?
关于java - 如何使用 GZIPInputStream 修复 EOF 读取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62093617/