DevKB
Web Development Knowledge Base
HOME | TOP 20 | WRITE AN ARTICLE |
Sections :


RSS RSS Feed

Vous aussi, aidez les autres développeurs, publiez vos bouts de codes utiles et vos liens préférés ...
Publiez un article !


Valid HTML 4.0 Transitional

Plateforme d'envoi de gros fichiers en ligne
Script PHP de boutique en ligne
Mondes virtuels gratuits en 3D

Olivier Ligny - - 12/03/2008 - vue 779 fois

GZIP compression in Java

Here are 2 methods to compress/uncompress gzipped strings in Java.

You must add an import statement at the beginning of your file :
import java.util.zip.*;
import java.io.*;

The java code :

    public static String compressGZip(String uncompressed) {
        try {
            ByteArrayOutputStream baos  = new ByteArrayOutputStream();
            GZIPOutputStream gzos       = new GZIPOutputStream(baos);
     
            byte [] uncompressedBytes   = uncompressed.getBytes();
     
            gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
            gzos.close();
     
            return byteArrayToString(baos.toByteArray());
        }
        catch(IOException e) {
            return "";
        }
    }

   
    public static String uncompressGZip(String str) {
       
        try {
           
            GZIPInputStream gzipInputStream = new GZIPInputStream(new StringBufferInputStream(str));
            OutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = gzipInputStream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            gzipInputStream.close();
            out.close();
           
            String res = out.toString();
           
            return res;
       
        }
        catch(Exception e) {System.out.println("Error : "+e);return null;}       
       
    }
   




Write a comment :
Your name :     E-mail (optional) :

AntiSpam : please write the result of 827 x 354 =