1,需求
需求要求实现多个文件压缩为zip文件
2,代码
package com.example.demo;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZIP {
public static void compressFiles(String zipPathDir, String zipFileName, List<String> fileList) throws Exception{
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(zipPathDir + zipFileName)));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(zos));
File zipFile = new File(zipPathDir);
if (!zipFile.exists()) {
zipFile.mkdirs();
}
for (String filePath : fileList) {
File file = new File(filePath);
if (file.exists()) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
Path path = Paths.get(filePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(path)));
while (reader.ready()) {
writer.write(reader.readLine());
}
writer.flush();
reader.close();
zos.closeEntry();
}else{
//文件路径异常filePath:filePath
}
}
zos.flush();
writer.close();
}
public static void main(String[] args) throws Exception{
String zipPathDir ="D://test/";
String zipFileName ="test.zip";
List<String> fileList = new ArrayList<>();
fileList.add("D://test/file.csv");
fileList.add("D://test/1.txt");
fileList.add("D://test/HelloWorld.txt");
compressFiles( zipPathDir, zipFileName, fileList);
}
}