压缩文件操作
public void zip(String sourceDir, String zipFilePath) {
try{
//创建zip输出流
OutputStream o = new FileOutputStream(zipFilePath);
ZipOutputStream out = new ZipOutputStream(o);
File sourceFile = new File(sourceDir);
//调用函数
compress(out,sourceFile,sourceFile.getName());
out.close();
o.close();
}catch(Exception e){
throw new RuntimeException("压缩失败 sourceDir="+sourceDir+",zipFilePath="+zipFilePath,e);
}
}
/**
* 进行压缩
* @param out
* @param bos
* @param sourceFile
* @param base
* @throws IOException
*/
private void compress(ZipOutputStream out, File sourceFile, String base) throws IOException {
//如果路径为目录(文件夹)
if(sourceFile.isDirectory()){
//取出文件夹中的文件(或子文件夹)
File[] flist = sourceFile.listFiles();
//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
if(flist.length==0){
out.putNextEntry(new ZipEntry(base+"/") );
}else{
//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
for(int i=0;i<flist.length;i++)
{
compress(out,flist[i],base+"/"+flist[i].getName());
}
}
}else{
//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
out.putNextEntry(new ZipEntry(base) );
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int BUFFER = 512;
byte[] buffer=new byte[BUFFER];
int readLength=0; //每次读取出来的长度
while ((readLength=bis.read(buffer,0,BUFFER))!=-1){
out.write(buffer,0,readLength);
}
bis.close();
fos.close();
}
}
解压文件操作
public void unzip(String zipSourceFilePath,String targetDir) {
File srcFile= new File(zipSourceFilePath);
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
String dirPath = targetDir + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(targetDir + "/" + entry.getName());
// 保证这个文件的父文件夹必须要存在
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if(zipFile != null){
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
项目衍生用法,多个图片压缩到同一个文件下
/**将多个图片文件以zip文件导出
* @param zipFileName
* @param fileList
* @param request
* @param response
* @throws Exception
*/
public static void downloadPicToZip(String zipFileName, List<Map<String,Object>> fileList,
HttpServletRequest request,HttpServletResponse response) throws Exception {
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
try {
String downloadZipFileName = zipFileName+".zip";
downloadZipFileName = URLEncoder.encode(downloadZipFileName, "UTF-8");// 转换中文否则可能会产生乱码
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
response.setHeader("Content-Disposition","attachment;filename="+downloadZipFileName);// 设置在下载框默认显示的文件名
for (int i = 0; i < fileList.size(); i++) {
Map<String,Object> fileMap = fileList.get(i);
zos.putNextEntry(new ZipEntry(zipFileName+File.separator+fileMap.get("name").toString()+ ".jpg"));
InputStream fis = getInputStreamByGet(fileMap.get("url").toString());
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
zos.flush();
zos.close();
}
}
private static InputStream getInputStreamByGet(String url) {
try {
HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
return inputStream;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}