java FTPClient下載多個檔案
阿新 • • 發佈:2019-01-05
最近有需求,要求從伺服器端下載多個檔案,並且下載的同時壓縮,上網查了半天沒有一個行的,最後還是想出下面的辦法,僅供參考
/** * 壓縮下載的資料夾 * @param namelist 下載的檔案列表 * @param path 下載路徑 * @param zipname 壓縮檔名稱 */ public void zipDownloadFile(HttpServletResponse response,List<String> namelist,String path,String zipname){ byte[] buf = new byte[1024]; try { // 本地儲存設定 response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipname, sysEncoding)+".zip"); response.setContentType("application/x-zip-compressed"); // 向本地寫檔案 ServletOutputStream sos=response.getOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(sos)); for (String name : namelist) { ZipEntry entry = new ZipEntry(name); zipOut.putNextEntry(entry); InputStream bis = this.getStream(path, name); if(bis!=null){ int readLen = -1; while ((readLen = bis.read(buf, 0, 1024)) != -1) { zipOut.write(buf, 0, readLen); } bis.close(); } } zipOut.close(); } catch (Exception e) { e.printStackTrace(); } }