文件压缩
public static void zipFiles() throws Exception{
//准备压缩的文件目录
File sourceFile = new File("/home/admin/YYY/templateFile");
//压缩后文件
File targetFile = new File("/home/admin/YYY/template.zip");
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(targetFile));
File[] listFiles = sourceFile.listFiles();
for (File file : listFiles) {
zipFile(out,file.getName(),file,true);
}
out.close();
}
/**
* KeepDirStructure:是否保留文件层级
**/
public static void zipFile(ZipOutputStream out,String fileName,File sourceFile,Boolean KeepDirStructure) throws IOException{
byte[] buf=new byte[1024];
if(sourceFile.isFile()){
FileInputStream in=new FileInputStream(sourceFile);
out.putNextEntry(new ZipEntry(fileName));
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.closeEntry();
in.close();
System.out.println(fileName+"压缩完成.");
}else{
File[] listFiles = sourceFile.listFiles();
if(listFiles==null||listFiles.length==0){
// 空文件夹的处理
out.putNextEntry(new ZipEntry(fileName + "/"));
// 没有文件,不需要文件的copy
out.closeEntry();
}else{
for (File file : listFiles) {
if(true==KeepDirStructure){
zipFile(out,fileName+"/"+file.getName(),file,KeepDirStructure);
}else{
zipFile(out,file.getName(),file,KeepDirStructure);
}
}
}
}
sourceFile.delete();
}