JAVA操作ZIP檔案

來源:互聯網
上載者:User

文章轉自:http://www.abcjava.com/html/JAVA/JAVAjichu/2009/1018/1080.html

更多學習資料:http://www.xcoder.cn 

在網路傳輸多個檔案的時候,如果一個一個傳往往會非常耗時,而且也會消耗掉更多的電腦系統資源。如果我們將多個檔案打包後再傳輸將會節約很多的電腦資源,這裡,我將為大家展示如何讀取、解壓和建立ZIP檔案,當然,這裡只是簡單介紹,關於zip檔案有很多細節需要大家自己去實現。關於java對zip的操作,主要是用的java.util.zip包中的類。

一、讀取ZIP檔案

ZipFile類用於從 ZIP 檔案讀取條目。所以,首先需要建立一個ZipFile對象,然後使用ZipFile對象的entries()方法擷取Zip檔案中的所有條目,具體代碼如下:

  1. public static void readZipFile(File file) { 
  2.     try { 
  3.         ZipFile zipfile = new ZipFile(file); //建立ZipFile對象
  4.         System.out.println(zipfile.getName()); //列印Zip檔案路徑
  5.         System.out.println("ZIP條目數:" + zipfile.size()); //列印Zip檔案條目數
  6.          
  7.         Enumeration<? extends ZipEntry> en = zipfile.entries(); 
  8.         ZipEntry entry; 
  9.         while(en.hasMoreElements()) { 
  10.             entry = en.nextElement(); 
  11.             System.out.println(entry.getName()); 
  12.         } 
  13.         zipfile.close(); 
  14.     }catch(ZipException e) { 
  15.         System.out.println(file.getName() + "壓縮檔錯誤"); 
  16.     }catch(IOException e) { 
  17.         System.out.println(file.getName() + "讀取檔案時出錯"); 
  18.     } 
  19. } 

聯繫我們

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