Java中檔案的壓縮處理

來源:互聯網
上載者:User

Java.util.zip 包中提供了可對檔案的壓縮和解壓縮進行處理的類,它們繼承自位元組流類OutputSteam 和 InputStream。其中 GZIPOutputStream 和 ZipOutputStream 可分別把資料壓縮成 GZIP 和 Zip 格式,GZIPInpputStream 和 ZipInputStream 又可將壓縮的資料進行還原。

將檔案寫入壓縮檔的一般步驟如下: 產生和所要產生的壓縮檔相關聯的壓縮類對象。 壓縮檔通常不只包含一個檔案,將每個要加入的檔案稱為一個壓縮入口,使用ZipEntry(String FileName)產生壓縮入口對象。 使用 putNextEntry(ZipEntry entry)將壓縮入口加入壓縮檔。 將檔案內容寫入此壓縮檔。 使用 closeEntry()結束目前的壓縮入口,繼續下一個壓縮入口。

將檔案從壓縮檔中讀出的一般步驟如下: 產生和所要讀入的壓縮檔相關聯的壓縮類對象。 利用 getNextEntry()得到下一個壓縮入口。

【例 10-13】輸入若干檔案名稱,將所有檔案壓縮為“ep10_13.zip”,再從壓縮檔中解壓並顯示。
//********** ep10_13.java **********
import java.io.*;
import java.util.*;
import java.util.zip.*;
class ep10_13{
    public static void main(String args[]) throws IOException{
        FileOutputStream a=new FileOutputStream("ep10_13.zip");
        //處理壓縮檔
        ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(a));
        for(int i=0;i<args.length;i++){  //對命令列輸入的每個檔案進行處理
            System.out.println("Writing file"+args[i]);
            BufferedInputStream in=new BufferedInputStream(new FileInputStream(args[i]));
            out.putNextEntry(new ZipEntry(args[i]));  //設定 ZipEntry 對象
            int b;
            while((b=in.read())!=-1)
                out.write(b);  //從源檔案讀出,往壓縮檔中寫入
            in.close();
        }
        out.close();
        //解壓縮檔案並顯示
        System.out.println("Reading file");
        FileInputStream d=new FileInputStream("ep10_13.zip");
        ZipInputStream  inout=new  ZipInputStream(new BufferedInputStream(d));
        ZipEntry z;

        while((z=inout.getNextEntry())!=null){  //獲得入口
            System.out.println("Reading file"+z.getName());  //顯示檔案初始名
            int x;
            while((x=inout.read())!=-1)
                System.out.write(x);
            System.out.println();
        }
        inout.close();
    }
}
例 10-13 運行後,在程式目錄建立一個 ep10_13.zip 的壓縮檔,使用解壓縮軟體(如 WinRAR等),可以將其開啟。命令提示字元下,程式運行結果如圖 10-12 所示:
圖 10-12  例 10_13 運行結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.