compress String with Gzip - Android File Input Output

Android examples for File Input Output:Zip File

Description

compress String with Gzip

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.util.zip.GZIPOutputStream;
import android.util.Base64;

public class Main {
    public static String compress(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }/*w  ww .  j  ava2s  . co  m*/
        byte[] tArray = null;
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out);
            gzip.write(str.getBytes("UTF-8"));
            gzip.flush();
            gzip.close();
            tArray = out.toByteArray();
            out.close();
            return Base64.encodeToString(tArray, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials