我正在尝试读取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)
答案 0 :(得分:3)
通过使用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”?