compress String with Charset with GZip - Android File Input Output

Android examples for File Input Output:Zip File

Description

compress String with Charset with GZip

Demo Code


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.android.volley.NetworkResponse;

public class Main{
    /**/*  w w  w  .j  a va  2 s.  co  m*/
     * 
     * @param str
     * @param charset
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    public static byte[] compress(String str, String charset)
            throws IOException, UnsupportedEncodingException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        try {
            gzip.write(str.getBytes(charset));
            gzip.close();
            return out.toByteArray();
        } catch (Exception e) {
            throw new IOException(e);
        } finally {

            if (gzip != null) {
                gzip.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
    
    public static byte[] compress(byte[] buffer) throws IOException,
            UnsupportedEncodingException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        try {
            gzip.write(buffer);
            gzip.close();
            return out.toByteArray();
        } finally {

            if (gzip != null) {
                gzip.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

Related Tutorials