最近碰到了一個按GZIP解壓指定的輸入流數據,備份下java
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * 壓縮,解壓類 */ public class ZipUtils { /** * 壓縮指定的字符串 * * @param str * @return * @throws IOException */ public static byte[] compress(String str) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(str.getBytes()); gzip.close(); return out.toByteArray(); } /** * 解壓縮字節數組 * * @param b * @return * @throws IOException */ public static byte[] uncompress(byte[] b) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(b); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } return out.toByteArray(); } // 測試方法 public static void main(String[] args) throws IOException { } }
注意事項數組
解壓方法最後不要轉成字符串 out.toString(); 不然解壓的時候會出現 Not in GZIP format 錯誤測試