java I/O:解壓ZIP文件並保存其目錄結構

 import java.util.*;
import java.util.zip.*;
import java.io.*;
import java.lang.*;

 

public class Unzip {

 /**
  * @param args
  */
 byte doc[]=null;
 String Filename=null;
 String unzipPath=null;
 
 public Unzip(String filename,String unzippath)
 {
  Filename=filename;
  unzipPath=unzippath;
  SetUnZipPath(unzipPath);
 }
 
 public Unzip(String filename)
 {
  Filename=filename;
  unzipPath=null;
  SetUnZipPath(unzipPath);
 }
 
 private void SetUnZipPath(String unzippath)
 {
  if(unzippath.endsWith("//"))   //String類的endsWith(char c)用與判斷字符串最後一個字符是否與c相同
   unzipPath=new String(unzippath);
  else
   unzipPath=new String(unzippath+"//");
 }
 
 public void doUnZip()
 {
  try {
   ZipInputStream zin=new ZipInputStream(new FileInputStream(Filename));
   ZipEntry fentry;     //用於表示 ZIP 文件條目
   while((fentry=zin.getNextEntry())!=null)   //ZipInputStream類的geNextEntry()讀取下一個 ZIP 文件條目並將流定位到該條目數據的開始處。
   {
    if(fentry.isDirectory())  //判斷文件條目是否目錄條目
     checkFilePath(unzipPath+fentry.getName());
    else
    {
     String fname=new String(unzipPath+fentry.getName());
     FileOutputStream out=new FileOutputStream(fname);
     doc=new byte[512];
     int n;
     while((n=zin.read(doc, 0, 512))!=-1)out.write(doc,0,n);
                    out.close();
                    out=null;
                    doc=null;
    }
   }//while
   zin.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
 
 private void checkFilePath(String dirName)throws IOException
 {
  File dir=new File(dirName);
  if(!dir.exists())
   dir.mkdirs();
 }
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
        String zipFile=args[0];
        String unzippath=args[1]+"//";
        Unzip myZip=new Unzip(zipFile,unzippath);
        myZip.doUnZip();
 }
 

}

/*學習心得
 1.File類 
 mkdirs()    創建目錄


 2.ZipInputStream類    
 ZipEntry getNextEntry()  讀取下一個 ZIP 文件條目並將流定位到該條目數據的開始處。 
 int read(byte[] b, int off, int len)  從當前 ZIP 條目讀入字節數組,b爲緩衝區,off爲偏移量,len爲讀入字節的最大數


 3.ZipOutputStream類
 int write(byte[] b, int off, int len)  向當前 ZIP 條目寫入字節數組


 4.ZipEntry類
  isDirectory())  判斷文件條目是否目錄條目
 
 注意:Zip文件條目的讀取和寫入方式必須以字符數組爲緩衝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章