//文件名:myZip.java
import java.io.*;
import java.util.*;
import java.util.zip.*;
/**
* <p>Title: 文件壓縮和解壓</p>
* <p>Description: 使用ZipInputStream和ZipOutputStream對文件
* 和目錄進行壓縮和解壓處理</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: myZip.java</p>
* @version 1.0
*/
public class myZip{
/**
*<br>方法說明:實現文件的壓縮處理
*<br>輸入參數:String[] fs 壓縮的文件數組
*<br>返回類型:
*/
public void ZipFiles(String[] fs){
try{
String fileName = fs[0];
FileOutputStream f =
new FileOutputStream(fileName+".zip");
//使用輸出流檢查
CheckedOutputStream cs =
new CheckedOutputStream(f,new Adler32());
//聲明輸出zip流
ZipOutputStream out =
new ZipOutputStream(new BufferedOutputStream(cs));
//寫一個注釋
out.setComment("A test of Java Zipping");
//對多文件進行壓縮
for(int i=1;i<fs.length;i++){
System.out.println("Write file "+fs[i]);
BufferedReader in =
new BufferedReader(
new FileReader(fs[i]));
out.putNextEntry(new ZipEntry(fs[i]));
int c;
while((c=in.read())!=-1)
out.write(c);
in.close();
}
//關閉輸出流
out.close();
System.out.println("Checksum::"+cs.getChecksum().getValue());
}catch(Exception e){
System.err.println(e);
}
}
/**
*<br>方法說明:解壓縮Zip文件
*<br>輸入參數:String fileName 解壓zip文件名
*<br>返回類型:
*/
public void unZipFile(String fileName){
try{
System.out.println("讀取ZIP文件........");
//文件輸入流
FileInputStream fi =
new FileInputStream(fileName+".zip");
//輸入流檢查
CheckedInputStream csi = new CheckedInputStream(fi,new Adler32());
//輸入流壓縮
ZipInputStream in2 =
new ZipInputStream(
new BufferedInputStream(csi));
ZipEntry ze;
System.out.println("Checksum::"+csi.getChecksum().getValue());
//解壓全部文件
while((ze = in2.getNextEntry())!=null){
System.out.println("Reading file "+ze);
int x;
while((x= in2.read())!=-1)
//這裡是寫文件,write是以byte方式輸出。
System.out.write(x);
}
in2.close();
}catch(Exception e){
System.err.println(e);
}
}
/**
*<br>方法說明:讀取Zip文件列表
*<br>輸入參數:String fileName zip文件名
*<br>返回類型:Vector 文件列表
*/
public Vector listFile(String fileName){
try{
String[] aRst=null;
Vector vTemp = new Vector();
//zip文件對象
ZipFile zf = new ZipFile(fileName+".zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()){
ZipEntry ze2 = (ZipEntry)e.nextElement();
System.out.println("File: "+ze2);
vTemp.addElement(ze2);
}
return vTemp;
}catch(Exception e){
System.err.println(e);
return null;
}
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] args){
try{
String fileName = args[0];
myZip myZip = new myZip();
myZip.ZipFiles(args);
myZip.unZipFile(fileName);
Vector dd = myZip.listFile(fileName);
System.out.println("File List: "+dd);
}catch(Exception e){
e.printStackTrace();
}
}
}