Skip to content

Instantly share code, notes, and snippets.

@jonathanalves
Last active July 4, 2019 13:52
Show Gist options
  • Save jonathanalves/c11e8dcb7bc4c4c7b2dcd42bba190a3e to your computer and use it in GitHub Desktop.
Save jonathanalves/c11e8dcb7bc4c4c7b2dcd42bba190a3e to your computer and use it in GitHub Desktop.
Java gzip compress/decompress string
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class Gzip {
public static byte[] compress(String data) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
return compressed;
}
public static String decompress(final byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
byte[] bytes = IOUtils.toByteArray(gis);
return new String(bytes, "UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment