Java 如何使用GZIPInputStream修复EOF读取错误
我试图读取gzip文件的内容并从中创建一个文件。我遇到了一个我看不出来的问题。如有任何建议,我们将不胜感激。多谢各位Java 如何使用GZIPInputStream修复EOF读取错误,java,file,gzip,eofexception,gzipinputstream,Java,File,Gzip,Eofexception,Gzipinputstream,我试图读取gzip文件的内容并从中创建一个文件。我遇到了一个我看不出来的问题。如有任何建议,我们将不胜感激。多谢各位 private static String unzip(String gzipFile, String location){ try { FileInputStream in = new FileInputStream(gzipFile); FileOutputStream out = new FileOutput
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)
通过使用确保正确关闭文件,您将使自己的生活更加轻松。例如:
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”?你可以通过使用来确保文件正确关闭,从而使自己的生活更加轻松。例如:
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”您确定输入文件有效吗?请注意while循环中的
buffer
变量不存在(您的意思可能是b
),您确定输入文件有效吗?请注意while循环中的buffer
变量不存在(您可能是指b
)