你的位置:首页 > Java教程

[Java教程]打包并下载文件


  CdncontractbillDAO billDAO = new CdncontractbillDAO();
    List billlist = billDAO.findAll();
//要下载的zip文件,名为DownLoad.zip
File zipFile = new File(System.getProperty("cdncharge_pdf")+"DownLoad.zip");
    try {
//用这个构造最终压缩包的输出流 
    ZipOutputStream zipoutStream = new ZipOutputStream(new FileOutputStream(zipFile));
    InputStream is;
    byte[] bufferArea = new byte[1024];//读写缓冲区
//循环所有文件,将文件打包
  for(Object bi : billlist){
      Cdncontractbill bill = (Cdncontractbill)bi;
      File file = new File(bill.getPath());
if(file.exists()){
FileInputStream zipinSource = new FileInputStream(file);
int read = 0;
ZipEntry zipEntry = new ZipEntry(file.getName());
zipoutStream.putNextEntry(zipEntry);//定位到该压缩条目位置,开始写入文件到压缩包中
while((read = zipinSource.read(bufferArea, 0, 1024)) != -1)
{
zipoutStream.write(bufferArea, 0, read);
}
zipoutStream.closeEntry();
zipinSource.close();
}
  }
  zipoutStream.close();
  is = new FileInputStream(zipFile);
  Filedownload.save(is, "", zipFile.getName());
} catch (Exception e) {
e.printStackTrace();
}
    //删除生成的打包文件
    zipFile.delete();