Compress String and return a String - Java java.lang

Java examples for java.lang:byte Array Compress

Description

Compress String and return a String

Demo Code


//package com.java2s;
import java.io.*;
import java.util.zip.*;
import sun.misc.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String data = "java2s.com";
        System.out.println(Compress(data));
    }/*from  w w  w.ja v  a  2 s  . c  om*/

    public static String Compress(String data) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DeflaterOutputStream zos = new DeflaterOutputStream(bos);
            zos.write(data.getBytes("GB2312"));
            zos.close();
            return new String(new BASE64Encoder().encode(bos.toByteArray()))
                    .replaceAll("\r", "").replaceAll("\n", "");
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
}

Related Tutorials