title: Compress and Decompress String in Java
body: <p>I'm trying to compress and decompress a string from producer and consumer environment (which accepts only string as params). </p>
  
  <p>So after I compress a string, I'm converting compressed byte array to string and then passing it to producer. 
  Then in consumer part, I'm taking the string back , converting into byte array and then decompressing the string from bytes. </p>
  
  <p>Instead of converting into string, if I used byte[], then it is working fine. But what I need is to convert into string and viceversa. </p>
  
  <p>Here is my code : </p>
  
  <pre><code>public class Compression {
  
  public static void main(String[] args) throws Exception{
      // TODO Auto-generated method stub
  
      String strToCompress = "Helloo!! ";
      byte[] compressedBytes = compress(strToCompress);
  
      String compressedStr = new String(compressedBytes, StandardCharsets.UTF_8);
      byte[] bytesToDecompress = compressedStr.getBytes(StandardCharsets.UTF_8);
  
      String decompressedStr = decompress(bytesToDecompress);
  
      System.out.println("Compressed Bytes : "+Arrays.toString(compressedBytes));
  
      System.out.println("Decompressed String : "+decompressedStr);
  
  }
  
  public static byte[] compress(final String str) throws IOException {
      if ((str == null) || (str.length() == 0)) {
        return null;
      }
      ByteArrayOutputStream obj = new ByteArrayOutputStream();
      GZIPOutputStream gzip = new GZIPOutputStream(obj);
      gzip.write(str.getBytes("UTF-8"));
      gzip.flush();
      gzip.close();
      return obj.toByteArray();
    }
  
    public static String decompress(final byte[] compressed) throws IOException {
      final StringBuilder outStr = new StringBuilder();
      if ((compressed == null) || (compressed.length == 0)) {
        return "";
      }
      if (isCompressed(compressed)) {   //It is not going into this if part
        final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
  
        String line;
        while ((line = bufferedReader.readLine()) != null) {
          outStr.append(line);
        }
      } else {
        outStr.append(compressed);
      }
      return outStr.toString();
    }
  
    public static boolean isCompressed(final byte[] compressed) {
      return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) &amp;&amp; (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC &gt;&gt; 8));
    }
  
  }
  </code></pre>