The problem is that you are not closing the GZIPOutputStream
. Until you close it the output will be incomplete.
You just need to close it before reading the byte array. You need to reorder the finally
blocks to achieve this.
import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;
public class Zipper
{
public static void main(String[] args)
{
byte[] dataToCompress = "This is the test data."
.getBytes(StandardCharsets.ISO_8859_1);
try
{
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(dataToCompress.length);
try
{
GZIPOutputStream zipStream =
new GZIPOutputStream(byteStream);
try
{
zipStream.write(dataToCompress);
}
finally
{
zipStream.close();
}
}
finally
{
byteStream.close();
}
byte[] compressedData = byteStream.toByteArray();
FileOutputStream fileStream =
new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
try
{
fileStream.write(compressedData);
}
finally
{
try{ fileStream.close(); }
catch(Exception e){ /* We should probably delete the file now? */ }
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I do not recommend inititalizing the stream variables to null
, because it means your finally
block can also throw a NullPointerException
.
Also note that you can declare main
to throw IOException
(then you would not need the outermost try
statement.)
There is little point in swallowing exceptions from zipStream.close();
, because if it throws an exception you will not have a valid .gz file (so you should not proceed to write it.)
Also I would not swallow exceptions from byteStream.close();
but for a different reason - they should never be thrown (i.e. there is a bug in your JRE and you would want to know about that.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…