//文件名: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();
}
}
}
闽公网安备 35060202000074号