1、压缩文件到内存字节,不需要存储本地。
2、压缩文件存储到本地目录
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class ZipUtil {
/**
* 压缩到字节
* @param sourceFileNames 源文件列表 k-目标文件名字 v-源文件字节流
* @return 压缩到内存节流
*/
public static byte[] compress(Map<String, byte[]> sourceFileNames) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(bout));
try {
for (String fileName : sourceFileNames.keySet()) {
log.info("当前压缩文件" + fileName);
zos.putNextEntry(new ZipEntry(fileName));
zos.write(sourceFileNames.get(fileName));
zos.closeEntry();
}
} catch (Exception e) {
log.error("压缩文件异常:", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bout.toByteArray();
}
/**
* 压缩到文件
* @param sourceFileNames 源文件列表
* @param zipFileName 目标压缩文件
*/
public static void compress(List<String> sourceFileNames, String zipFileName){
byte[] buf = new byte[1024];
File zipFile = new File(zipFileName);
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for(int i = 0; i < sourceFileNames.size(); i++){
File sourceFile = new File(sourceFileNames.get(i));
FileInputStream fis = new FileInputStream(sourceFile);
zos.putNextEntry(new ZipEntry(sourceFile.getName()));
log.info("压缩当前文件:{}",sourceFile.getName());
int len;
while((len = fis.read(buf)) > 0){
zos.write(buf, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
System.out.println("压缩完成");
} catch (Exception e) {
log.error("压缩文件异常:",e);
}
}
public static void main(String[] args) throws Exception {
// 压缩在内存
Map<String, byte[]> sourceFileNames = new HashMap(16);
byte[] b1 = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\1.jpg")));
byte[] b2 = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\2.jpg")));
byte[] b3 = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\3.jpg")));
byte[] b4 = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\4.jpg")));
// a b c d 为制定压缩后的文件名字
sourceFileNames.put("a.jpg", b1);
sourceFileNames.put("b.jpg",b2);
sourceFileNames.put("c.jpg",b3);
sourceFileNames.put("d.jpg",b4);
compress(sourceFileNames);
// 压缩到本地文件夹
List<String> sourceFileToLocal = new ArrayList<>();
sourceFileToLocal.add("D:\\Desktop\\1.jpg");
sourceFileToLocal.add("D:\\Desktop\\2.jpg");
String zipFileName = "D:\\Desktop\\test\\test.zip";
compress(sourceFileToLocal,zipFileName);
// IOUtils 读取文件
// byte[] oriSign = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\1031.ok")));
// System.out.println("原签名串"+new String(oriSign));
}
}