英文:
How to fix EOF read error with GZIPInputStream
问题
我正在尝试读取一个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: ZLIB输入流意外结束
在java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)中
在java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)中
在java.util.zip.GZIPInputStream.read(GZIPInputStream.java:116)中
在java.io.FilterInputStream.read(FilterInputStream.java:107)中
英文:
I am trying to read the contents of a gzip file and create a file from it. I'm running into an issue that I can't see to figure out. Any ideas of suggestion is appreciated. Thank you.
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)
答案1
得分: 3
使用资源块可以让您的生活变得更加轻松,确保您的文件被正确关闭。例如:
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文件(当然!)并且您的输入和输出文件名是不同的。
至于"buffer"是怎么回事?我猜您可能是指"b"(GPI也是这么认为的)。
英文:
You'll make life much easier on yourself by using Resource Blocks to ensure your files are closed correctly. For example:
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();
}
}
You should also ensure you've got a valid .zip file (of course!) and that your input and output filenames are different.
And what's going on with "buffer"? I assume (as does GPI) you probably meant "b"?
专注分享java语言的经验与见解,让所有开发者获益!
评论