Java将多文件打成压缩包
package com.filezip;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author wuYuHua
* @version 1.0.0
* @ClassName Example.java
* @Description 示例
* @createTime 2022年09月13日 17:05:00
*/
public class Example {
private static final String OUT = "H:/temp";
private static final String FILE_ONE_PATH = "H:\\zip\\node-v16.17.0-x64.msi";
private static final String FILE_TWO_PATH = "H:\\zip\\nvm-setup.exe";
public static void main(String[] args) {
List<File> files = new ArrayList<>();
// 获取两个文件
File fileOne = new File(FILE_ONE_PATH);
File fileTwo = new File(FILE_TWO_PATH);
files.add(fileOne);
files.add(fileTwo);
try {
zipFile(files);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void zipFile(List<File> fileList) throws IOException {
// 文件的压缩包路径
String zipPath = OUT+"/"+System.currentTimeMillis()+".zip";
// 获取文件压缩包输出流
try (OutputStream outputStream = new FileOutputStream(zipPath);
CheckedOutputStream checkedOutputStream = new CheckedOutputStream(outputStream,new Adler32());
ZipOutputStream zipOut = new ZipOutputStream(checkedOutputStream)){
for (File file : fileList) {
// 获取文件输入流
InputStream fileIn = new FileInputStream(file);
// 使用 common.io中的IOUtils获取文件字节数组
byte[] bytes = IOUtils.toByteArray(fileIn);
// 写入数据并刷新
zipOut.putNextEntry(new ZipEntry(file.getName()));
zipOut.write(bytes,0,bytes.length);
zipOut.flush();
fileIn.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
版权声明:本文为qq_42511655原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。