问题
某天产品baba,提了一个需求,企业下载文件压缩包,需要按类别归类全部的文件。压缩包结构如下图:
某某企业文件.zip | ||
文件夹1 | ||
a.jpg | ||
b.jpg | ||
文件夹2 | ||
a.jpg | ||
b.jpg | ||
文件夹3 | ||
a.jpg |
解决办法
找了网上很多方法,基本都是压缩包里面直接放文件的。
经过自己多次跳坑终于找到可行办法,
关键就是方法的路径写法,如下:
(zos.putNextEntry(new ZipEntry("文件夹"+i + File.separator + sourceFile.getName()));)。
文件夹名称+ 分隔符 +文件名
代码如下:
package com.example.demo;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Description: 带文件夹的压缩
* @author: luog
* @Date: 2021/1/20
* @param: null
* @returns:
*/
public class Common {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* @Description: 生成带目录的文件压缩包
* @author: luog
* @Date: 2021/1/20
* @param: srcDir 源文件路径
* @param: outDir 最终文件名
* @param: KeepDirStructure
* @returns: void
*/
public static void createZip(String srcDir, String outDir) throws RuntimeException, Exception {
byte[] buf = new byte[BUFFER_SIZE];
try {
File sourceFile = new File(srcDir);
ZipOutputStream zos = null;
OutputStream out = new FileOutputStream(new File(outDir));
//模拟生成是三个文件夹 每个文件夹放一个文件
for (int i = 0; i < 3; i++) {
//web 请求请用response 构建输出流
// response.setCharacterEncoding("gb2312");
// response.setHeader("Content-Disposition", "attachment; filename=企业文件.zip");
// zos = new ZipOutputStream(response.getOutputStream());
//本地测试用 用输出文件路径和名称 构建输出流
zos = new ZipOutputStream(out);
zos.putNextEntry(new ZipEntry("文件夹"+i + File.separator + sourceFile.getName()));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
}
zos.close();
System.out.println("压缩完成");
} catch (Exception e) {
throw e;
}
}
/**
* @Description: 本地测试
* @author: luog
* @Date: 2021/1/21
* @param: args
* @returns: void
*/
public static void main(String[] args) throws Exception {
//本地文件路径
String localDir="D:\\img1\\xx.jpg";
//输出文件路径和名称
String outDir = "D:\\某某企业全部文件.zip";
createZip(localDir, outDir);
}
}
最终效果截图;
注意:web 请求请用response 构建输出流
希望能帮到你!!!
点个赞吧!!!