JAVA文件打包ZIP

来源:互联网 发布:老豆咪索茄 知乎 编辑:程序博客网 时间:2024/05/16 12:49

今天项目中需要打包zip网上找了找,整理了几个得出自己的打包理解,特此一记

package com.amdox.busi.media.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* 文件打包工具类
* @author julong
* @date 2016年5月9日 上午11:09:14
*/
public class ZipUtil {
/**
* 日志
* @author julong
* @date 2016年5月9日 上午11:10:26
*/
private static final Logger logger = LoggerFactory.getLogger(ZipUtil.class);
/**
* 文件上传路径
* @author julong
* @date 2016年5月9日 下午3:23:01
*/
public static final String uploadPath = "C://";

/**
* zip包存放地址
* @author julong
* @date 2016年5月9日 下午3:23:41
*/
public static final String zipPath = "C://";
/**
* 文件打包的方法
* @param files 文件信息集合(文件的存放完整路径名称)
* @param savePath 存储打包文件的路径
* @return true文件打包成功 false 文件打包失败
* @author julong
* @date 2016年5月9日 上午11:12:43
*/
public static boolean createFilesToZip(List<File> files,String savePath){
logger.info("文件开始打包....");
boolean result = false;
//定义字节流
byte[] buffer = new byte[1024];
//定义zip流
ZipOutputStream out = null;
try {
//定义打包文件名和存放的路径
logger.info("当前保存文件的名称和存储路径是:"+savePath);
out = new ZipOutputStream(new FileOutputStream(savePath));
if(null != files && !files.isEmpty()){
logger.info("此次打包文件一共:"+files.size());
for(int i=0;i<files.size();i++) {
File file = files.get(i);
//判断文件是否为空
if(file.exists()){
//创建输入流
FileInputStream fis = new FileInputStream(file);
//获取文件名
String name = file.getName();
//创建zip对象
ZipEntry zipEntry = new ZipEntry(name);
out.putNextEntry(zipEntry);
int len;
//读入需要下载的文件的内容,打包到zip文件
while((len = fis.read(buffer))>0) {
out.write(buffer,0,len);
}
out.closeEntry();
fis.close();
}
}
}
out.close();
logger.info("文件打包完毕....");
result = true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(null != out){
try {
out.close();
} catch (IOException e) {
}
}
}
return result;
}




/**
* 测试方法
* @param args
* @author julong
* @date 2016年5月9日 上午11:10:34
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
byte[] buffer = new byte[1024];
//生成的ZIP文件名为Demo.zip
String strZipName = "C:/zip23.zip";
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));
//需要同时下载的两个文件result.txt ,source.txt
File[] file1 = {new File("c:/a.txt"),new File("c:/b.txt"),new File("c:/c.txt"),new File("c:/d.txt")};
for(int i=0;i<file1.length;i++) {
FileInputStream fis = new FileInputStream(file1[i]);
out.putNextEntry(new ZipEntry(file1[i].getName()));
int len;
//读入需要下载的文件的内容,打包到zip文件
while((len = fis.read(buffer))>0) {
out.write(buffer,0,len);
}
out.closeEntry();
fis.close();
}
out.close();
} catch (Exception e) {
// TODO: handle exception
}
}

}

0 0
原创粉丝点击