2014-10-20 130 views
1

我希望遞歸讀取壓縮文件的內容並將所有找到的文件保存到我的硬盤驅動器。如何閱讀壓縮文件的內容並保存文件

我讀的zip文件是這樣的:

def zipFile = new java.util.zip.ZipFile(new File('/Users/birdy/test.zip')) 

zipFile.entries().findAll { !it.directory }.each { 
    def is = zipFile.getInputStream(it) 
    //how do i store this stream to a file? 
} 

如果一個zip文件有下列文件:

folder1/test1.txt 
folder2/test2.jpg 

的話,我希望存儲test1.txttest2.jpg我HD

回答

2

這裏你去:

import java.util.zip.* 

def zipIn = new File('lol.zip') 
def zip = new ZipFile(zipIn) 

zip.entries().findAll { !it.directory }.each { e -> 
    (e.name as File).with{ f -> 
     f.parentFile?.mkdirs() 
     f.withOutputStream { w -> 
      w << zip.getInputStream(e) 
     } 
    } 
} 

一切都清楚了嗎?

+0

幾件事情:首先,'文件可能不存在的'新文件(e.name)的父目錄。其次,爲什麼'withWriter'而不是'withInputStream'?這不是假設的人物數據? – bdkosher 2014-10-20 17:10:11

+0

當涉及到父目錄時,如果您在處理zip的相同目錄中運行腳本,它將會存在。 Steam改變了。 – Opal 2014-10-20 17:14:11

+0

Zip條目名稱不一定是一個深度的路徑元素。在某些情況下,條目的父目錄需要在本地文件系統上創建,但不幸的是,當你開始向文件寫入內容時,這不會自動發生。你需要一個明確的'mkdirs()'調用。 – bdkosher 2014-10-20 17:41:14

0

Java代碼

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.util.List; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipInputStream; 

public class UnZip 
{ 
    List<String> fileList; 
    private static final String INPUT_ZIP_FILE = "C:\\MyFile.zip"; 
    private static final String OUTPUT_FOLDER = "C:\\outputzip"; 

    public static void main(String[] args) 
    { 
     UnZip unZip = new UnZip(); 
     unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER); 
    } 

    /** 
    * Unzip it 
    * @param zipFile input zip file 
    * @param output zip file output folder 
    */ 
    public void unZipIt(String zipFile, String outputFolder){ 

    byte[] buffer = new byte[1024]; 

    try{ 

     //create output directory is not exists 
     File folder = new File(OUTPUT_FOLDER); 
     if(!folder.exists()){ 
      folder.mkdir(); 
     } 

     //get the zip file content 
     ZipInputStream zis = 
      new ZipInputStream(new FileInputStream(zipFile)); 
     //get the zipped file list entry 
     ZipEntry ze = zis.getNextEntry(); 

     while(ze!=null){ 

      String fileName = ze.getName(); 
      File newFile = new File(outputFolder + File.separator + fileName); 

      System.out.println("file unzip : "+ newFile.getAbsoluteFile()); 

      //create all non exists folders 
      //else you will hit FileNotFoundException for compressed folder 
      new File(newFile.getParent()).mkdirs(); 

      FileOutputStream fos = new FileOutputStream(newFile);    

      int len; 
      while ((len = zis.read(buffer)) > 0) { 
      fos.write(buffer, 0, len); 
      } 

      fos.close(); 
      ze = zis.getNextEntry(); 
     } 

     zis.closeEntry(); 
     zis.close(); 

     System.out.println("Done"); 

    }catch(IOException ex){ 
     ex.printStackTrace(); 
    } 
    }  
} 
+1

Java太冗長了.. – Opal 2014-10-20 16:35:03