javaarraysgzipoutputstream

Convert GZIPOutputStream to byte array


I already have a GZIPOutput stream which has already defined. Now I want to convert it to a byte array.

I tried the code below. But it gives an error.

GZIPOutputStream zipStream = createGZIP();
byte[] compressedData = zipStream.toByteArray();

error : cannot resolve method "toByteArray()"

checked GZIP compression to a byte array , but it is inputting a byte[]. I need to convert a gzip which I already have.


Solution

  • I have a GZIPOutput stream which has already defined. Now I want to convert it to a byte array.

    You will need to modify the method that is creating the GZIPOutputStream so that it sends it to a ByteArrayOutputStream.

    Alternatively, after closing the FileOutputStream for the file where you are (presumably) writing the compressed data, open it for input and read it into a byte array.


    Concerning your current attempt:

    GZIPOutputStream zipStream = createGZIP();
    byte[] compressedData = zipStream.toByteArray();
    

    This approach is not going to work.

    In general, it is better to find and read the javadocs for the classes that you use. Programming by guessing what methods they provide is liable to lead you to waste your time when your guess are wrong.