Skip to content

Instantly share code, notes, and snippets.

@fairjm
Created July 15, 2015 10:50
Show Gist options
  • Save fairjm/39b2458b5ccfa77515f6 to your computer and use it in GitHub Desktop.
Save fairjm/39b2458b5ccfa77515f6 to your computer and use it in GitHub Desktop.
public class StringCompressUtil {
private static final String DEFAULT_ENCODING = "UTF-8";
public static String compress(final String str) throws IOException {
if (StringUtils.isEmpty(str)) {
return str;
}
String result;
try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
// must close gzip first or the out will be empty anyway
try (final GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(str.getBytes(DEFAULT_ENCODING));
}
result = out.toString(CharEncoding.ISO_8859_1);
}
return result;
}
public static String uncompress(final String str) throws IOException {
if (StringUtils.isEmpty(str)) {
return str;
}
String result;
try (final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ByteArrayInputStream in = new ByteArrayInputStream(
str.getBytes(CharEncoding.ISO_8859_1));
final GZIPInputStream gunzip = new GZIPInputStream(in);) {
// from commons IO IOUtils simply replace it by while read and write
IOUtils.copy(gunzip, out);
result = out.toString(DEFAULT_ENCODING);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment