Skip to content

Instantly share code, notes, and snippets.

@yblee85
Last active January 11, 2024 12:50
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yblee85/70d5bba26196e9dc4270 to your computer and use it in GitHub Desktop.
Save yblee85/70d5bba26196e9dc4270 to your computer and use it in GitHub Desktop.
java gzip convert string to gzip / gzip to string
package gzip;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipTest {
public static void main(String[] args) throws Exception {
String string = "test gzip. this will compress and decompress this string";
System.out.println("after compress:");
byte[] compressed = compress(string);
System.out.println(compressed);
System.out.println("after decompress:");
String decomp = decompress(compressed);
System.out.println(decomp);
}
public static byte[] compress(String str) throws Exception {
if (str == null || str.length() == 0) {
return null;
}
System.out.println("String length : " + str.length());
ByteArrayOutputStream obj=new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(str.getBytes("UTF-8"));
gzip.close();
return obj.toByteArray();
}
public static String decompress(byte[] str) throws Exception {
if (str == null ) {
return null;
}
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(str));
BufferedReader bf = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
String outStr = "";
String line;
while ((line=bf.readLine())!=null) {
outStr += line;
}
System.out.println("Output String lenght : " + outStr.length());
return outStr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment