package com.pactera.zipUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将多个文件压缩成zip文件
* @author pactera
*
*/
public class ZipUtil {
public static final int BUFFER = 2048;
public static void zip(String [] filename, String destFile) throws Exception{
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
FileOutputStream dest = new FileOutputStream(destFile);
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i = 0;i < filename.length;i++){
//读取待压缩的文件
File file = new File(filename[i]);
FileInputStream fi = new FileInputStream(file);
origin = new BufferedInputStream(fi,BUFFER);
//创建zip实体,并添加进压缩包
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
//写进压缩包
int count;
while((count = origin.read(data,0,BUFFER)) != -1){
out.write(data, 0, count);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//关闭流
if(origin != null){
origin.close();
}
if(out != null){
out.close();
}
}
}
public static void main(String[] args) throws Exception {
zip(new String [] {"c://a.txt","d://c.docx"}, "c://c.zip");
}
}
//可以将多个文件进行压缩,
1.文件输出字符流将文件输出到指定目录.
2.压缩字节流将文件输出字符流进行压缩控制.
3.使用文件输入流来读取文件进入内存.
4.创建zip实体,并将文件添加进压缩包.
5.写入数据进压缩包.
6.关闭流.