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



RSS RSS Feed

You too, please publish your useful code snippets in any programming language :
write an article !


Valid HTML 4.0 Transitional

Plateforme d'envoi de gros fichiers en ligne
Dépannage site web
Blog infogérance
Hébergement e-mail

Olivier Ligny - - 12/03/2008 - vue 9884 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;}       
       
    }
   


- 27/07/2012
change:
GZIPInputStream gzipInputStream = new GZIPInputStream(new StringBufferInputStream(str));
to:
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(str.getBytes()));


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

AntiSpam : what animal is visible on this picture ? :

Nos partenaires : iPhone 8 Cases & Protection