Tuesday, 29 March 2016

Decoding with base-64 and un-GZIP-ing the encoded string


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.codec.binary.Base64;

public static String decodeBase64AndUnGzip(String inputStr) 
    throws IOException {
     int BUFFER_SIZE = 4096;
     byte[] buffer = new byte[BUFFER_SIZE];
        
     // decode the input string using base 64
     byte[] decodedStr = Base64.decodeBase64(inputStr);
     // Get the GZIP input stream
     InputStream input = new GZIPInputStream( 
                          new ByteArrayInputStream(decodedStr) );
     // Make a byte array in memory
     ByteArrayOutputStream output = new ByteArrayOutputStream();
     // Read the un-GZIPed contents and
     // write to byte array stream using buffer
     int n = input.read(buffer, 0, BUFFER_SIZE);
     while (n >= 0) {
         output.write(buffer, 0, n);
         n = input.read(buffer, 0, BUFFER_SIZE);
     }

     // make a byte array from byte array stream
     byte[] strOut = output.toByteArray();
        
     // close the streams
     output.close();
     input.close();
        
     return new String(strOut);
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.