import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
public class ZipUtils {
/**
* @param response
* @param fileList 多文件列表
* @param zipPath 壓縮的文件暫存的目錄,下載后會刪除掉
*/
public static void zipFiles(HttpServletResponse response, List<File> fileList, File zipPath) {
// 1 文件壓縮
if (!zipPath.exists()) { // 判斷壓縮后的文件存在不,不存在則創建
try {
zipPath.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fileOutputStream=null;
ZipOutputStream zipOutputStream=null;
FileInputStream fileInputStream=null;
try {
fileOutputStream=new FileOutputStream(zipPath); // 實例化 FileOutputStream對象
zipOutputStream=new ZipOutputStream(fileOutputStream); // 實例化 ZipOutputStream對象
ZipEntry zipEntry=null; // 創建 ZipEntry對象
for (int i=0; i<fileList.size(); i++) { // 遍歷源文件數組
fileInputStream = new FileInputStream(fileList.get(i)); // 將源文件數組中的當前文件讀入FileInputStream流中
zipEntry = new ZipEntry(fileList.get(i).getName()); // 實例化ZipEntry對象,源文件數組中的當前文件
zipOutputStream.putNextEntry(zipEntry);
int len; // 該變量記錄每次真正讀的字節個數
byte[] buffer=new byte[1024]; // 定義每次讀取的字節數組
while ((len=fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
fileOutputStream.close();
// 2 文件下載
long currentTime=System.currentTimeMillis(); // 當時時間戳
int randomFour=(int)((Math.random()*9+1)*1000); // 4位隨機數
String fileName=String.valueOf(currentTime)+String.valueOf(randomFour)+".zip"; // 新的文件名稱
String path=zipPath.toString();
// 設置輸出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循環取出流中的數據
FileInputStream inStream=new FileInputStream(path); // 讀到流中
byte[] b = new byte[100];
int len;
try {
OutputStream os=response.getOutputStream();
response.setContentType("application/octet-stream");
while ((len = inStream.read(b)) > 0){
os.write(b, 0, len);
}
inStream.close();
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try { // 3 刪除壓縮包
String path=zipPath.toString();
File zfile = new File(path);
zfile.delete();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
controller調用:
@RequestMapping(value = "/batchDownload.do", method = RequestMethod.GET) public void batchDownload(HttpServletRequest request, HttpServletResponse response) {
try { //ZipUtils.zipFiles(); } catch (Exception e) { e.printStackTrace(); System.out.println("batchDownload error"); } }