java GZIP压缩和解压
生活随笔
收集整理的這篇文章主要介紹了
java GZIP压缩和解压
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
最近碰到了一個按GZIP解壓指定的輸入流數據,備份下
?
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 錯誤
?
轉載于:https://www.cnblogs.com/duanxingxing/p/5502868.html
總結
以上是生活随笔為你收集整理的java GZIP压缩和解压的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ArcGIS空间分析笔记(汤国安)
- 下一篇: 行为科学统计第3章