I have to unzip a .gz file for which I am using following code:
FileInputStream fis = null;
FileOutputStream fos = null;
GZIPInputStream gin = null;
try {
File file = new File(getPath(), zipName);
fis = new FileInputStream(file);
gin = new GZIPInputStream(fis);
File newFile = // some initialization related to path and name
fos = new FileOutputStream(getPath());
byte[] buf = new byte[1024];
int len;
while ((len = gin.read(buf)) > 0) {
fos.write(buf, 0, len);
}
gin.close();
fos.close();
//newFile is ready
} catch(IOException e){
// exception catch
}
However when the client gz file is corrupt I am getting following error :
Exception in thread "main" java.io.EOFException: Unexpected end of ZLIB input stream
at java.util.zip.InflaterInputStream.fill(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.util.zip.GZIPInputStream.read(Unknown Source)
at java.util.zip.InflaterInputStream.read(Unknown Source)
Surprisingly the file is still getting ungzipped and store at a local location. I do not want a corrupt file to be ungzipped or processed further at all.
One way could be to delete the newFile object when catch clause is hit with java.io.EOFException
, but is that a right approach? There could be some other possible exceptions as well when the file wasnt corrupt.
Reference @EJP
If you get any IOException for any reason, from corrupt input to the disk flying into orbit around Pluto, you should delete the output file and treat the operation as a failure. You don't have to think beyond that. – EJP