parent
40e549e74c
commit
dbba662368
@ -0,0 +1,73 @@ |
||||
package com.ruoyi.system.util.ziputil; |
||||
|
||||
import java.io.File; |
||||
import java.io.FileInputStream; |
||||
import java.io.FileOutputStream; |
||||
import java.io.IOException; |
||||
import java.util.List; |
||||
import java.util.zip.ZipEntry; |
||||
import java.util.zip.ZipOutputStream; |
||||
|
||||
/** |
||||
* @author liangjiawei |
||||
* @createDate 2024/7/25 |
||||
*/ |
||||
public class ZipFilesUtils { |
||||
// 假设这是根据文件ID查询到的文件路径集合
|
||||
public static List<String> getFilePathsById() { |
||||
// 示例:返回文件路径集合
|
||||
return List.of( |
||||
"/Users/liangjiawei/Downloads/worddocx/file/2-10.docx","/Users/liangjiawei/Downloads/worddocx/file/2-11.docx","/Users/liangjiawei/Downloads/worddocx/file/2-12.docx","/Users/liangjiawei/Downloads/worddocx/file/2-13.docx","/Users/liangjiawei/Downloads/worddocx/file/2-14.docx" |
||||
); |
||||
} |
||||
|
||||
public static void compressFiles(List<String> filePaths, String zipFilePath) throws IOException { |
||||
try (FileOutputStream fos = new FileOutputStream(zipFilePath); |
||||
ZipOutputStream zos = new ZipOutputStream(fos)) { |
||||
for (String filePath : filePaths) { |
||||
File file = new File(filePath); |
||||
if (!file.exists()) { |
||||
System.out.println("文件不存在: " + filePath); |
||||
continue; |
||||
} |
||||
addFileToZip(file, zos, ""); |
||||
} |
||||
} |
||||
} |
||||
|
||||
private static void addFileToZip(File file, ZipOutputStream zos, String parentDir) throws IOException { |
||||
if (file.isDirectory()) { |
||||
String dirPath = parentDir + file.getName() + File.separator; |
||||
zos.putNextEntry(new ZipEntry(dirPath)); |
||||
zos.closeEntry(); |
||||
for (File subFile : file.listFiles()) { |
||||
addFileToZip(subFile, zos, dirPath); |
||||
} |
||||
} else { |
||||
try (FileInputStream fis = new FileInputStream(file)) { |
||||
ZipEntry zipEntry = new ZipEntry(parentDir + file.getName()); |
||||
zos.putNextEntry(zipEntry); |
||||
byte[] buffer = new byte[1024]; |
||||
int length; |
||||
while ((length = fis.read(buffer)) > 0) { |
||||
zos.write(buffer, 0, length); |
||||
} |
||||
zos.closeEntry(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
public static void main(String[] args) { |
||||
String fileId = "exampleFileId"; // 示例文件ID
|
||||
String zipFilePath = "/Users/liangjiawei/Downloads/worddocx/file/zip/output.zip"; // 输出压缩文件路径
|
||||
|
||||
try { |
||||
List<String> filePaths = getFilePathsById(); |
||||
compressFiles(filePaths, zipFilePath); |
||||
System.out.println("压缩成功,文件路径: " + zipFilePath); |
||||
} catch (IOException e) { |
||||
e.printStackTrace(); |
||||
System.err.println("压缩失败!"); |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue