import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Gzip compressed strings */ public class GZIP { /** * String compression * @param str String to be compressed * @return returns the compressed string * @throws IOException */ public static String compress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } // create a new output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); // Create new output stream with default buffer size GZIPOutputStream gzip = new GZIPOutputStream(out); // write bytes to this output stream gzip.write(str.getBytes("utf-8")); //Because the default character set in the background may be the GBK character set, a character set needs to be specified here gzip.close(); // Convert the buffer contents to a string by decoding the bytes using the specified charsetName return out.toString("ISO-8859-1"); } /** * Decompression of strings * @param str decompress the string * @return returns the decompressed string * @throws IOException */ public static String unCompress(String str) throws IOException { if (null == str || str.length() <= 0) { return str; } // create a new output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); // Create a ByteArrayInputStream using buf as its buffer array ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("ISO-8859-1")); // Create new input stream with default buffer size GZIPInputStream gzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n = 0; // read uncompressed data into byte array while ((n = gzip.read(buffer)) >= 0){ out.write(buffer, 0, n); } // Convert the buffer contents to a string by decoding the bytes using the specified charsetName return out.toString("utf-8"); } }
GZIP application
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=326762203&siteId=291194637
Ranking