GZIPとは?
データ圧縮技術
現在一般的に使用されている圧縮アルゴリズムは次のとおりです。
GZIP は、圧縮率が高く低速なアルゴリズムであり、圧縮されたデータは長期間の使用に適しています。JDK の java.util.zip.GZIPInputStream/GZIPOutputStream は、このアルゴリズムの実装です。
deflate は、GZIP と同様に、gzip とは異なり、圧縮時間と出力ファイル サイズのバランスをとることができるアルゴリズムの圧縮レベルを指定できます。オプションのレベルは 0 (圧縮なし)、および 1 (高速圧縮) ~ 9 (圧縮が遅い)、その実装は java.util.zip.Deflater/Inflater です。
GZIP の基本原則
Gzip は圧縮に deflate アルゴリズムを使用するため、gzip の基本原理は deflate の基本原理でもあります。圧縮するファイルは、まず LZ77 アルゴリズムの変種を圧縮し、得られた結果にハフマン エンコーディング方式を使用します (gzip は、状況に応じて静的ハフマン エンコーディングまたは動的ハフマン エンコーディングの使用を選択します)。
LZ77 アルゴリズム
ファイル内に同じ内容の断片が 2 つある場合、前の断片の位置とサイズがわかれば、次の断片の内容を判断でき、(2 つの断片間の距離) などの情報を使用できます。 、同じコンテンツの長さ) を置き換えて、後者をコンテンツの一部に置き換えます。(2 つの間の距離、同じコンテンツの長さ) ペアのサイズは、置き換えられたコンテンツのサイズよりも小さいため、ファイルは圧縮されます。
データ圧縮用の GZIP
package com.lingxu;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtil {
/**
* @Description: 加密
* @author: Ajie
* @date: 2022/5/11
* @param str
* @return: byte[]
*/
public static byte[] compress(String str) {
ByteArrayOutputStream out =null;
GZIPOutputStream gzip=null;
try{
if (str == null || str.length() == 0) {
return null;
}
out = new ByteArrayOutputStream();
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes("ISO-8859-1"));
gzip.finish();
return out.toByteArray();
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
try{
if(out!=null){
out.close();
}
if(gzip!=null){
gzip.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* @Description: 解密
* @author: Ajie
* @date: 2022/5/11
* @param by
* @return: java.lang.String
*/
public static String unCompress(byte []by) {
ByteArrayOutputStream out=null;
GZIPInputStream gunzip=null;
try{
if(by==null || by.length==0){
return "";
}
out=new ByteArrayOutputStream();
gunzip= new GZIPInputStream(new ByteArrayInputStream(by));
byte[] buffer = new byte[1024];
int n;
while ((n=gunzip.read(buffer))!=-1) {
out.write(buffer, 0, n);
}
out.flush();
return new String(out.toByteArray(),"ISO-8859-1");
}catch(Exception e){
e.printStackTrace();
return "";
}finally{
try{
if(out!=null){
out.close();
}
if(gunzip!=null){
gunzip.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
String str = "ADSaksdnkjasdhfoWEFHOwhenfouuishefiuqhwieufwieuhrfiuqwheriuhqweiurhwqeiurh";
System.out.println(str.getBytes("utf-8").length);
System.out.println(compress(str).length);
System.out.println(unCompress(compress(str)));
}
}