Skip to content

Instantly share code, notes, and snippets.

@gbzarelli
Created June 15, 2022 20:29
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 gbzarelli/bdde9c4e23872abd97a21475c10221ce to your computer and use it in GitHub Desktop.
Save gbzarelli/bdde9c4e23872abd97a21475c10221ce to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
interface Gzip {
static byte[] compress(String data) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length())) {
try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
gzip.write(data.getBytes(StandardCharsets.UTF_8));
}
return bos.toByteArray();
}
}
static String decompress(byte[] compressed) throws IOException {
final var sb = new StringBuilder();
try (ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
BufferedReader br = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment