Sections :
RSS Feed
You too, please publish your useful code snippets in any programming language : write an article !
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 10016 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()));
|