您的位置:首页 > 运维架构 > Apache

java zip 批量打包(java.util包和apache.tools包)

2016-07-29 15:15 447 查看
/**
* 文件批量打包
* @param zipPath  打包路径
* @param files  批量文件
*/
public void zipOut(String zipPath,File[] files){
byte[] buffer = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
for(int i=0;i<files.length;i++) {
FileInputStream fis = new FileInputStream(files[i]);
out.putNextEntry(new ZipEntry(files[i].getName()));
int len;
//读入需要下载的文件的内容,打包到zip文件
while((len = fis.read(buffer))>0) {
out.write(buffer,0,len);
}
out.closeEntry();
fis.close();
//删除文件,可以不删
files[i].delete();
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("生成zip文件成功");
}


以上为java.util包zip的压缩方式,弊端是不能修改编码。下面介绍apache.tools包zip的压缩方式。

/**
* 创建ZIP文件
* @param zipPath 生成的zip文件存在路径(包括文件名)
* @param files  写入的文件
*/
public static void zipOut(String zipPath,File[] files) {
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(zipPath);
zos = new ZipOutputStream(fos);
writeZip(files, zos);
} catch (FileNotFoundException e) {
System.out.println("创建ZIP文件失败");
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
System.out.println("创建ZIP文件失败");
}

}
}
/**
* 写入内容
* @param files
* @param zos
*/
private static void writeZip(File[] files, ZipOutputStream zos) {
for(int i=0;i<files.length;i++) {
if(files[i].exists()){
FileInputStream fis=null;
DataInputStream dis=null;
try {
fis=new FileInputStream(files[i]);
dis=new DataInputStream(new BufferedInputStream(fis));
ZipEntry ze = new ZipEntry(files[i].getName());
zos.putNextEntry(ze);
//添加编码,如果不添加,当文件以中文命名的情况下,会出现乱码
// ZipOutputStream的包一定是apache的ant.jar包。JDK也提供了打压缩包,但是不能设置编码
zos.setEncoding("GBK");
byte [] content=new byte[1024];
int len;
while((len=fis.read(content))!=-1){
zos.write(content,0,len);
zos.flush();
}
} catch (FileNotFoundException e) {
System.out.println("创建ZIP文件失败");
} catch (IOException e) {
System.out.println("创建ZIP文件失败");
}finally{
try {
if(dis!=null){
dis.close();
}
}catch(IOException e){
System.out.println("创建ZIP文件失败");
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: