1.Snappy-java項目地址
https://github.com/xerial/snappy-java
2.Snappy-java兩種壓縮方式
使用Snappy.compress進行壓縮
String dataString = "The quick brown fox jumps over the lazy dog"; byte[] compressed = Snappy.compress(dataString.getBytes("UTF-8")); byte[] uncompressed = Snappy.uncompress(compressed); String result = new String(uncompressed, "UTF-8"); System.out.println(result);
使用SnappyInputStream進行壓縮
public static byte[] compressSnappy(byte[] data) throws IOException { ByteArrayInputStream is = new ByteArrayInputStream(data); ByteArrayOutputStream os = new ByteArrayOutputStream(); SnappyOutputStream sos = new SnappyOutputStream(os); int count; byte temp[] = new byte[BUFFER]; try { while ((count = is.read(temp)) != -1) { sos.write(temp, 0, count); } sos.flush(); byte[] output = os.toByteArray(); return output; } finally { sos.close(); is.close(); } }
3.兩種壓縮方式的區別
/** * 輸出如下: * Snappy.compress 壓縮結果:2b a8 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 66 6f 78 20 6a 75 6d 70 73 20 6f 76 65 72 20 74 68 65 20 6c 61 7a 79 20 64 6f 67 * SnappyInputStream壓縮結果:82 53 4e 41 50 50 59 00 00 00 00 01 00 00 00 01 00 00 00 2d 2b a8 54 68 65 20 71 75 69 63 6b 20 62 72 6f 77 6e 20 66 6f 78 20 6a 75 6d 70 73 20 6f 76 65 72 20 74 68 65 20 6c 61 7a 79 20 64 6f 67 * |---------------------magic header(16bytes)-----|size(4bytes)|----compressed data----- */ @Test public void testSnappyCompress() throws Exception { String dataString = "The quick brown fox jumps over the lazy dog"; byte[] compressedData = Snappy.compress(dataString.getBytes()); System.out.println("Snappy.compress 壓縮結果:" + bytes2hex(compressedData)); byte[] compressedData2 = compressSnappy(dataString.getBytes()); System.out.println("SnappyInputStream壓縮結果:" + bytes2hex(compressedData2)); } /** * 將byte數組按16進制的方式輸出 */ public static String bytes2hex(byte[] bytes) { StringBuilder sb = new StringBuilder(); String tmp = null; for (byte b : bytes) { // 將每個字節與0xFF進行與運算,然后轉化為10進制,然后借助於Integer再轉化為16進制 tmp = Integer.toHexString(0xFF & b); if (tmp.length() == 1) { tmp = "0" + tmp; } sb.append(tmp).append(" "); } return sb.toString(); }
區別如下:
通過Snappy.compress()進行壓縮,壓縮后的數據沒有magic header
通過SnappyInputStream進行壓縮,壓縮后的數據有固定的header