compress String with GZIP - Java File Path IO

Java examples for File Path IO:GZIP

Description

compress String with GZIP

Demo Code


//package com.java2s;

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

import java.nio.ByteBuffer;

import java.util.zip.GZIPOutputStream;

public class Main {
    public static byte[] compress(String string) throws IOException {
        byte[] blockcopy = ByteBuffer.allocate(4)
                .order(java.nio.ByteOrder.LITTLE_ENDIAN)
                .putInt(string.length()).array();
        ByteArrayOutputStream os = new ByteArrayOutputStream(
                string.length());//from  w w  w .  ja  v a 2s  . com
        GZIPOutputStream gos = new GZIPOutputStream(os);
        gos.write(string.getBytes());
        gos.close();
        os.close();
        byte[] compressed = new byte[4 + os.toByteArray().length];
        System.arraycopy(blockcopy, 0, compressed, 0, 4);
        System.arraycopy(os.toByteArray(), 0, compressed, 4,
                os.toByteArray().length);
        return compressed;
    }
}

Related Tutorials