包含压缩文件或文件夹、压缩多个文件或文件夹、按数量分段压缩文件夹 使用带缓冲的输入流提高压缩速度
package com.client.util;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileZip {
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
BufferedInputStream in=new BufferedInputStream(new FileInputStream(f));
byte[] b=new byte[1024];
int len=0;
while ((len=in.read(b)) != -1) {
out.write(b,0,len);
}
in.close();
}
}
public static void zipDir(String dirPath,String zipName){
File file=new File(dirPath);
if(file.isDirectory()){
File[] files = file.listFiles();
FileUtil.createIfNoExist( dirPath+"\\"+zipName,true);
try(ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(dirPath + "\\" + zipName))
){
zip(zipOutputStream,files,"");
zipOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void zip(ZipOutputStream out,File[] files,String base) throws Exception {
for (int i = 0; i < files.length; i++) {
zip(out, files[i], base +files[i].getName());
}
}
public static void zip(String zipPathname,File[] files){
FileUtil.createIfNoExist(zipPathname,true);
try(ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(zipPathname))
){
zip(zipOutputStream,files,"");
zipOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void partitionZipDir(String dirPath,int itemsPerZip){
File dir=new File(dirPath);
if(!dir.isDirectory())throw new RuntimeException(dirPath+" 不是目录");
File[] files = dir.listFiles();
int total= files.length/itemsPerZip;
if(files.length%itemsPerZip!=0)total++;
System.out.println("压缩文件数:"+total);
int zipCount=1;
int start,end;
while (true){
System.out.println("("+zipCount+"/"+total+")");
start=(zipCount-1)*itemsPerZip;
end=zipCount*itemsPerZip-1;
if(end>= files.length)end= files.length-1;
File[] partFiles=new File[end-start+1];
System.arraycopy(files, start, partFiles, 0, partFiles.length);
zip(dirPath+"/zipPart"+zipCount+".zip",
partFiles);
if(end>= files.length-1)break;
zipCount++;
}
}
public static void zipFile(String filePathname,String zipPathname){
File file=new File(filePathname);
if(file.isFile()){
FileUtil.createIfNoExist( zipPathname,true);
try(ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(zipPathname))
){
zip(zipOutputStream,file,"");
zipOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String [] temp){
partitionZipDir("E:\\a",10);
}
}
|