打包成具有相同结构的zip文件,空文件夹结构将不会创建
* @param parentPath
父级目录,也将会是解压后的目录名称,如果为空,则解压后会有多个目录
* @param pathMap
以目录名称为 key,HashMap《String,Object》做为value,表示当前节点为文件夹
以任意key,List《String》为value,表示当前节点下的所有文件
* @param zipStream
输出流,打包好的文件将会被写入该流,该流需调用者手动关闭
* @param basePath
文件的基础路径,将会拼接在pathMap中的每一个路径之前
*/
[email protected]("unchecked")
public static void compressIntoZip(String parentPath,HashMappathMap,ZipOutputStream zipStream,String basePath) {
if(parentPath == null) parentPath = "";
System.out.println(parentPath);
// 按照类型进行分级,如果是map,则为 目录,list,则为 文件
for (String key : pathMap.keySet()) {
Object obj = pathMap.get(key);
// 如果是目录
if(obj instanceof HashMap) {
compressIntoZip(parentPath + "/" + key,(HashMap)obj,zipStream,basePath);
}else if(obj instanceof List) {
// 如果是文件
ListpathList = (List)obj;
for (String path : pathList) {
System.out.println(parentPath + "/" + path);
// 打包操作
try (
FileInputStream zipSource = new FileInputStream(new File(basePath + "/" + path));
BufferedInputStream bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
){
// 文件位置结构,"/"结尾为目录,其他为文件
ZipEntry zipEntry = new ZipEntry(parentPath + "/" + new File(basePath + "/" + path).getName());
zipStream.putNextEntry(zipEntry);
byte[] buff = new byte[1024 * 10];
int len = 0;
// 写入流
while ((len = bufferStream.read(buff, 0, 1024 * 10)) != -1) {
zipStream.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
// 测试
public static void main(String args[]) {
// 输出名
String fileName = "客户资料打包";
// D:/TestFile/ 目录下的文件
Listlist = new ArrayList();
list.add("meihuashisan.jpg");
list.add("pretty,scenery.jpg");
list.add("pretty,yeah.jpg");
list.add("shisan#wuliuqi.jpg");
list.add("test - test$t.jpg");
HashMapmap = new CustomBean()
.put("客户1",
new CustomBean()
.put("产品附件", new CustomBean().put(null, list))
.put("订单附件", new CustomBean().put(null, list))
.put("其他附件", new CustomBean().put(null, list))
).put("客户2",
new CustomBean()
.put("产品附件", new CustomBean().put(null, list))
.put("订单附件", new CustomBean().put(null, list))
.put("其他单附件", new CustomBean().put(null, list))
);
try (
ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(new File("D:/" + fileName + ".zip")))
){
compressIntoZip(fileName,map, zipStream,"D:/TestFile");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* 适用链式编程的一个自定义字段实体
* @author luoyudetian
*
*/
static class CustomBean extends HashMap{
private static final long serialVersionUID = 1L;
[email protected]
public CustomBean put(String key,Object value){
super.put(key, value);
return this;
}
}