Skip to content

Instantly share code, notes, and snippets.

@Crydust
Created May 25, 2018 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Crydust/34eaac18d1a61be92d96611e98fc4bba to your computer and use it in GitHub Desktop.
Save Crydust/34eaac18d1a61be92d96611e98fc4bba to your computer and use it in GitHub Desktop.
gzip compress and dencompress byte arrays in java 8
public static byte[] compress(final byte[] bytes) throws IOException {
if (bytes == null || bytes.length == 0) {
return new byte[0];
}
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final OutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(bytes);
}
return out.toByteArray();
}
public static byte[] decompress(final byte[] bytes) throws IOException {
if (bytes == null || bytes.length == 0) {
return new byte[0];
}
try (final GZIPInputStream ungzip = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] data = new byte[8192];
int nRead;
while ((nRead = ungzip.read(data)) != -1) {
out.write(data, 0, nRead);
}
return out.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment