java打包下載下傳檔案,需要使用apache的ant.jar,代碼如下:
public void exportAllQrCode(HttpServletRequest request,HttpServletResponse response){
List<StoreInformation> storeList = storeInformationService.getAllByList();
String urlStr = "";
try {
String fileName = "aa.zip";
File f = new File(request.getRealPath("")+"/temp");
if(!f.exists()){
f.mkdir();
}
String outFilePath = request.getRealPath("")+"/temp/"+fileName;
File file = new File(outFilePath);
ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[];
DataInputStream dataInputStream = null;
String siid = "";
String siname = "";
if(storeList!=null && storeList.size()>){
for(int i=;i<storeList.size();i++){
siid = storeList.get(i).getSiid();
siname = storeList.get(i).getSiname();
urlStr = Utils.getBasePath(request)+"/code/pic/"+siid+".jpg";
URL url = new URL(urlStr);
dataInputStream = new DataInputStream(url.openStream());
zipout.setEncoding("GBK");
zipout.putNextEntry(new ZipEntry(siname+".jpg"));
int len = ;
while((len=dataInputStream.read(buffer))>){
zipout.write(buffer, , len);
}
zipout.closeEntry();
dataInputStream.close();
}
}
zipout.close();
LOGGER.info("***********zip檔案生成成功*********");
//******URL中帶中文****//
urlStr = Utils.getBasePath(request)+"/temp/"+fileName;
URL url = new URL(urlStr);
DataInputStream ds = new DataInputStream(url.openStream());
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int length = ;
while((length=ds.read(buffer))!=-){
out.write(buffer, , length);
out.flush();
}
ds.close();
out.close();
file.delete();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
throw new RuntimeException("生成壓縮包時,源檔案不存在:"+urlStr, e);
} catch (IOException e) {
e.printStackTrace();
}
}