压缩代码:
public class FileZipUtil {
/**
* @description:将文件/文件夹生成指定格式的压缩文件
* @autor:ym10159
* @date:2017年12月22日 上午9:53:13
* @param srcPath 源文件路径
* @param targetPath 压缩文件保存路径
*/
public static void compressedFile(String srcPath, String targetPath, String zipFileName){
File srcFile = new File(srcPath);
File targetFile = new File(targetPath);
//压缩目录不存在,则创建
if (targetFile.isDirectory() && !targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream fos = null;
ZipOutputStream zos = null;
try {
fos = new FileOutputStream(targetPath + File.separator + zipFileName);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
compress(zos, srcFile, "");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null != zos){
zos.close();
}
if(null != fos){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void compress(ZipOutputStream zos, File file, String baseDir) throws Exception {
if (file.isDirectory()) {
baseDir = file.getName() + File.separator;
compressDir(zos, file, baseDir);
} else if (file.isFile()){
compressFile(zos, file, baseDir);
}
}
private static void compressDir(ZipOutputStream zos, File file, String baseDir) throws Exception{
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
/**递归调用*/
compress(zos, files[i], baseDir);
}
}
private static void compressFile(ZipOutputStream zos, File file, String baseDir) throws Exception{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
zos.putNextEntry(new ZipEntry(baseDir + file.getName()));
int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) != -1) {
zos.write(buffer, 0, len);
}
bis.close();
}
}
注意点:
1.流的关闭顺序,否则会报stream closed异常
2.递归的调用
下载代码:
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{
String zipDownloadPath = attachmentService.download(orderCodeList);
File file = new File(zipDownloadPath);
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.setCharacterEncoding("UTF-8");
String filename = file.getName().replaceAll("\\s", "");
filename = URLEncoder.encode(filename,"UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
}
注意点:
1.下载弹出框的设置,
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename));
2.在谷歌和火狐浏览器中,不能更改目录存放,火狐默认存放在桌面,谷歌默认存放在C:\Users\用户名\Downloads下。而QQ浏览器有更改目录的功能。至于在谷歌和火狐浏览器中,不能更改存放目录的原因暂时还未解决。有解决的人,记得告诉我答案。