public static void main(String[] args) { try { String longString = "www.baidu.com"; // GZIP压缩后的数据 byte[] compress = compress(longString.getBytes()); //通过Base64转成字符串 String longStringEncoded = Base64.getEncoder().encodeToString(compress); } catch (IOException e) { e.printStackTrace(); }} public static byte[] compress(byte[] data) throws IOException { if (data == null || data.length == 0) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(data); gzip.close(); return out.toByteArray();} public static byte[] uncompress(byte[] data) throws IOException { if (data == null || data.length == 0) { return null; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream inputStream = new ByteArrayInputStream(data); GZIPInputStream gzip = new GZIPInputStream(inputStream); byte[] buffer = new byte[256]; int n; while ((n = gzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } gzip.close(); inputStream.close(); return out.toByteArray();}
|