java - 从文件列表创建 zip(包括路径文件夹)
问题描述
我有一个应用程序,我目前可以在其中压缩选定文件的列表,即:
- /baseDir/folder_a/file_a.txt
- /baseDir/folder_b/folder_c/file_b.txt(排除)
- /baseDir/folder_b/folder_d/file_c.txt
目前我可以创建一个包含所有文件的 zip 文件。但是,不包括文件夹结构,所以我的 zip 看起来像这样:
- /zipFolder/file_a.txt
- /zipFolder/file_c.txt
由于我不想压缩文件夹中的所有文件,而只选择一个,所以我很难。有人可以给我提示如何添加文件,使其看起来像这样:
- /zipFolder/folder_a/file_a.txt
- /zipFolder/folder_b/folder_d/file_c.txt
这是我的代码:
public static byte[] zip(List<File> listFiles) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
for (File file : listFiles) {
if (file.isDirectory()) {
zipDirectory(file, file.getName(), zipOutputStream);
} else {
zipFile(file, zipOutputStream);
}
}
zipOutputStream.flush();
zipOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
private static void zipDirectory(File folder, String parentFolder, ZipOutputStream zos) throws IOException {
for (File file : folder.listFiles()) {
if (file.getName().endsWith(".zip")) {
continue;
}
if (file.isDirectory()) {
zipDirectory(file, parentFolder + "/" + file.getName(), zos);
continue;
}
zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
long bytesRead = 0;
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
bytesRead += read;
}
zos.closeEntry();
bis.close();
}
}
private static void zipFile(File file, ZipOutputStream zos) throws IOException {
zos.putNextEntry(new ZipEntry(file.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
long bytesRead = 0;
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
bytesRead += read;
}
zos.closeEntry();
bis.close();
}
解决方案
推荐阅读
- django - Django + postgreSQL 设置
- java - JDBC 库在 Android Studio 中不起作用
- javascript - 如何使用计数器获取对象属性
- oracle - 更改 Oracle 11g 系统密码
- outlook-web-addins - 有没有办法在“to”或“cc”字段中获取所有收件人?
- android - 有没有人从美国成功向中国腾讯应用商店提交安卓应用?
- java - 为什么要编译 Java 正则表达式?
- reactjs - React OnClick 函数不会绑定,“this”仍然显示未定义
- vhdl - VHDL 综合工具不会推断 FSM
- mysql - MySQL (5.7.21) 外键约束解析顺序