Created
June 15, 2022 20:29
-
-
Save gbzarelli/bdde9c4e23872abd97a21475c10221ce to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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