Java IO 之 ZipFile/ZipInputStream/ZipOutputStream

來源:互聯網
上載者:User

進行檔案操作時,一般的步驟如下:

讀操作:對目標檔案 new 一個輸入資料流      —>       讀取資料      —>      操作資料

寫操作:對目標檔案 new 一個輸出資料流      —>       調用write方法寫入資料   


瞭解Java壓縮技術首先應該瞭解Zip檔案的結構,如下圖,一個zip檔案包含了多個ZipEntry,稱之為“條目”。



zip檔案的操作和普通檔案的操作是類似的,唯一的區別是zip檔案的資料結構不同,zip檔案是個容器,包含多個檔案。因此對zip檔案的讀寫就是對容器內檔案的讀寫。

讀操作:對目標zip檔案 new 一個zip輸入資料流      —>      對於每個條目,為該條目new一個檔案輸入資料流,讀取條目資料     —>      操作資料

寫操作:對目標zip檔案 new 一個zip輸出資料流      —>      對於每個條目,為該條目new一個檔案輸出資料流,然後寫入資料   



讀操作的代碼:

@Testpublic void runZipInputStream() throws IOException {//1. 建立zip輸入資料流ZipInputStream zin = new ZipInputStream(new FileInputStream("IOTest.zip"));ZipEntry ze;//2. 逐個處理條目while ((ze = zin.getNextEntry()) != null) {//測試: 輸出條目的資訊System.out.printf("條目資訊: 名稱%1$b, 大小%2$d, 壓縮時間%3$d \n", ze.getName(), ze.getSize(), ze.getTime());//3. 操作檔案內容-輸出、處理FileInputStream fin = new FileInputStream(ze.getName());byte[] buffer = new byte[4096];int len;while ((len = fin.read(buffer)) != -1) {System.out.print(new String(buffer, 0, len));}}}

寫作業碼:

@Testpublic void runZipOutputStream() throws IOException {//1. 建立zip輸出資料流ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("javaio.rar"));//2. 建立並設定條目資訊File f = new File("javaio.bmp");ZipEntry ze = new ZipEntry(f.getName());ze.setComment("Hello, Zip");ze.setSize(f.length());ze.setTime(f.lastModified());//3. 添加條目到輸出資料流zos.putNextEntry(ze);//4. 輸出FileInputStream fin = new FileInputStream(f);byte[] buffer = new byte[4096];int len;while ((len = fin.read(buffer)) != -1) {zos.write(buffer, 0, len);}fin.close();//5. 關閉流zos.close();}

上面的代碼都是對單個檔案進行操作,如果要壓縮整個目錄,就需要遍曆目錄下的所有檔案。







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.