1.代码
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author zhlu
* @date 2019/9/24 11:30
*/
@Slf4j
public class ZipUtil {
private ZipUtil(){
throw new IllegalStateException("ZipUtil class");
}
/**
* 功能:压缩多个文件成一个zip文件
*
* @param srcfile:源文件列表
* @param zipfile:压缩后的文件
*/
public static void zipFiles(List<File> srcfile, File zipfile) {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile))) {
for (File f : srcfile) {
dealWithFile(f,out);
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
/**
* Description: 处理文件
* * @Param f
* @Param out
* @return void
* @author yxf
* @date 2019/8/22 3:10 PM
*/
private static void dealWithFile(File f,ZipOutputStream out){
byte[] buf = new byte[1024];
try(FileInputStream in = new FileInputStream(f)){
out.putNextEntry(new ZipEntry(f.getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
}catch (IOException e) {
log.error(e.getMessage());
}
}
/**
* Description: 处理文件名
* * @Param f
* @Param out
* @Param fileName
* @return void
* @author yxf
* @date 2019/8/22 3:10 PM
*/
private static void dealWithFileNames(File f, ZipOutputStream out, String fileName) {
byte[] buf = new byte[1024];
try (FileInputStream in = new FileInputStream(f)) {
out.putNextEntry(new ZipEntry(fileName));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
} catch (IOException e) {
log.error(e.getMessage());
}
}
/**
* 功能:压缩多个文件成一个zip文件,并用自定义文件名替换
*
* @param srcfile:源文件列表
* @param fileNames:文件名称列表
* @param zipfile:压缩后的文件
*/
public static void zipFiles(List<File> srcfile, List<String> fileNames, File zipfile) {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile))) {
int i = 0;
for (File f : srcfile) {
dealWithFileNames(f, out, fileNames.get(i));
i++;
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
/**
* 压缩map中的文件至压缩包中
* @param fileMap
* @param zipFile
*/
public static void packFile2Zip(Map<String, File> fileMap, File zipFile) {
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
Iterator<Map.Entry<String, File>> iterator = fileMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, File> entry = iterator.next();
String name = entry.getKey();
File file = entry.getValue();
dealWithFileNames(file,out,name);
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
public static void main(String[] args) {
//压缩文件集合
List<File> files = new ArrayList<>();
File file1=new File("E:\\PDF\\test\\test-1.jpg");
File file2=new File("E:\\PDF\\test\\test-2.jpg");
files.add(file1);
files.add(file2);
//新建一个压缩文件
File zipFile =new File("E:\\PDF\\test\\test.zip");
zipFiles(files,zipFile);
}
}
2.测试结果