其中主要的类:
ZipEntry 存储ZIP实体
ZipInputStream 一个输入过滤流,用来读取ZIP格式文件中的文件
ZipOutputStream 一个输出过滤流,用来向ZIP格式文件口写入文件
下面的程序演示了怎样利用java.util.zip包实现数据的压缩:
/**
* author suqiang
* create on 2008-7-26
*/
import java.io.*;
import java.util.zip.*;
public class Zip {
public static final int BUFFER = 1024;
public static void main(String[] args) {
try {
FileOutputStream dest = new FileOutputStream("C://SuQiang.zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
putToZip(new File("C://SuQiang"), out, "");
out.close();
}catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* put file(include directory) to zip file
* @param file:The file to be zipped
* @param out:The zipped file
* @param dir
* @throws IOException
*/
private static void putToZip(File file,ZipOutputStream out, String dir) throws IOException{
if(file.isDirectory()){
File[] files = file.listFiles();
dir = dir + (dir.length()==0 ?"":"/")+file.getName();
for(int i=0;i<files.length;i++)
putToZip(files[i],out,dir);
}else{
byte[]data = new byte[BUFFER];
FileInputStream fi = new FileInputStream(file);
BufferedInputStream origin = new BufferedInputStream(fi,BUFFER);
dir = dir.length()==0?"":dir+"/"+ file.getName();
ZipEntry entry = new ZipEntry(dir);
out.putNextEntry(entry);
int count;
while((count = origin.read(data,0,BUFFER))!= -1)
out.write(data,0,count);
origin.close();
fi.close();
}
}
}