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 錯誤

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM