Skip to content

Instantly share code, notes, and snippets.

@dynoChris
Created September 20, 2019 15:41
Show Gist options
  • Select an option

  • Save dynoChris/daadd54abcc16f15bd458ad1b125abfb to your computer and use it in GitHub Desktop.

Select an option

Save dynoChris/daadd54abcc16f15bd458ad1b125abfb to your computer and use it in GitHub Desktop.
How to gzip string in java. How to compress string to byte array.
private 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;
}
private String decompress(byte[] compressed) throws IOException {
ByteArrayInputStream bis;
bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis;
gis = new GZIPInputStream(bis);
BufferedReader br;
br = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
StringBuilder sb;
sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
gis.close();
bis.close();
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment