Java Gzip壓縮與解壓


package component;

import org.testng.annotations.Test;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class TestGZip {

    @Test
    public void testGZip() throws IOException {


                //做准備壓縮一個字符文件,這里的字符文件是UTF-8編碼方式的。注意使用字符流而不是字節流的原因:字節流不能設置讀取時候的編碼,
            //字符流可以設置讀取時候使用的編碼
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(
                        "D:\\IDEAworkspace\\testComponent\\src\\main\\resources\\zipsource\\source.txt"), "UTF-8"));
        //使用GZIPOutputStream包裝OutputStream流,使其具體壓縮特性,最后會生成test.txt.gz壓縮包
                BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(
                        new FileOutputStream("D:\\IDEAworkspace\\testComponent\\src\\main\\resources\\zipsource\\test.txt.gz")));
                System.out.println("開始寫壓縮文件...");
                int c;
                //每次循環讀取一個字符的數據,並寫一個字符的數據到壓縮包中。
                while ((c = in.read()) != -1) {
                    out.write(String.valueOf((char) c).getBytes("UTF-8"));
                }
                in.close();
                out.close();


                System.out.println("開始讀壓縮文件...");
                //使用GZIPInputStream包裝InputStream流,使其具有解壓特性
                BufferedReader in2 = new BufferedReader(new InputStreamReader(
                        new GZIPInputStream(new FileInputStream("D:\\IDEAworkspace\\testComponent\\src\\main\\resources\\zipsource\\test.txt.gz")), "UTF-8"));
                String s;
                //以行為單位來讀取壓縮文件里的內容
                while ((s = in2.readLine()) != null) {
                    System.out.println(s);
                }
                in2.close();


    }
}

 

參考:https://www.cnblogs.com/visec479/p/4112881.html


免責聲明!

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



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