之前使用java.util.zipoutputstream发现压缩文件内中文文件名出现乱码,尝试使用URLEncoder.encode(fileName, "UTF-8")/URLEncoder.encode(fileName, "GBK")均无效。后来从网友will_443238794博客https://blog.csdn.net/will_443238794/article/details/78957504处得知新知识点,原来java.util.zipoutputstream无法设置字符集,建议使用org.apache.tools.zip.ZipOutputStream
但我的实际需求是zip中有多个文件,故略微改造...
public void downloadBatchByFile(HttpServletResponse response, Map<String, byte[]> files, String zipName){
try{
response.reset();
//zipName = URLEncoder.encode(zipName, "ISO8859_1");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8") + ".zip");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(zos);
zos.setEncoding("gbk");//设置中文编码
for(Map.Entry<String, byte[]> entry : files.entrySet()){
String fileName = zipName+"-"+entry.getKey();//每个zip文件名
byte[] file = entry.getValue();//这个zip文件的字节
BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file));
zos.putNextEntry(new ZipEntry(fileName+".xml"));
int len = 0;
byte[] buf = new byte[10 * 1024];
while( (len=bis.read(buf, 0, buf.length)) != -1){
bos.write(buf, 0, len);
}
bis.close();
bos.flush();
}
bos.close();
}catch(Exception e){
e.printStackTrace();
}
}