java web把文件夾內的文件打成壓縮包下載

直接上代碼

                File zipFile = FileUtil.downLoadZIP(request,response,imgPath,zipPath,zipName);//對應下面的downLoadZip方法
		
		FileInputStream zipInput = null;
		 OutputStream out = null;
		try {
			zipInput = new FileInputStream(zipFile);
		    out = response.getOutputStream();
		    response.setContentType("application/octet-stream");
		    response.setHeader("Content-Disposition", "attachment; filename="+zipName);
		    int len = 0;
		    byte[] buf = new byte[1024*10];
		    while ((len=zipInput.read(buf,0,1024*10))!= -1){  
		            out.write(buf,0,len);  
		    }
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				zipInput.close();
				out.flush();
				out.close();
				//刪除壓縮包
				zipFile.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}



/**
	 * 把文件夾內的文件打成zip壓縮包
	 * @Title: downLoadZIP 
	 * @Description: TODO 
	 * @param request
	 * @param response
	 * @param imgPath	文件夾路徑
	 * @param zipPath 	壓縮包路徑
	 * @param zipName 	壓縮包名字
	 * @return File		壓縮包file
	 * @author wanghb
	 * @date 2018年5月9日下午3:58:17
	 */
	public static File downLoadZIP(HttpServletRequest request, HttpServletResponse response, String imgPath,
			String zipPath, String zipName) {
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		ZipOutputStream zos = null;
		FileOutputStream fos = null;
		File imgPathFile = new File(imgPath);
		int num = 10240;
		if (!imgPathFile.exists()) {
			throw new RuntimeException("圖片路徑不存在");
		}
		File zipPathFile = new File(zipPath);
		if (!zipPathFile.exists()) {
			zipPathFile.mkdirs();
		}
		File zipFile = new File(zipPath + zipName);
		if (zipFile.exists()) {
			zipFile.delete();
		}
		File[] listFiles = imgPathFile.listFiles();
		if (null == listFiles && listFiles.length < 1) {
			throw new RuntimeException("目錄上沒有文件");
		}
		try {
			fos = new FileOutputStream(zipFile);
			zos = new ZipOutputStream(new BufferedOutputStream(fos));
			byte[] bytebus = new byte[num];
			int read = 0;
			for (int i = 0; i < listFiles.length; i++) {
				File file = listFiles[i];
				ZipEntry ze = new ZipEntry(file.getName());
				zos.putNextEntry(ze);
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				while ((read = bis.read(bytebus, 0, num)) != -1) {
					zos.write(bytebus, 0, read);
				}
				zos.closeEntry();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (zos != null) {
					zos.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return zipFile;
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章