標籤:類 打包 zipoutputstream
今天跟大家聊聊使用ZipOutputStream打包下載,我下面是使用ant的jar打包的,因為他對應中文的支援比較好
大家也可以使用java.util.zip包裡面的工具類打包,但是他對於中文不友好,很多都是亂碼的(包括注釋、檔案名稱、打包名)
import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;
/** * 打包下載 * * @param response */private void downFile(HttpServletResponse resp,ArrayList<String> filePathList) throws ServletException,IOException {// 標頭檔resp.setContentType("APPLICATION/OCTET-STREAM");resp.setHeader("Content-Disposition","attachment; filename=" + this.getZipFilename());// 壓縮檔ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());// --拼裝ArrayList<File> fileList = new ArrayList<File>();for (int i = 0; i < filePathList.size(); i++) {File file = new File(filePathList.get(i));fileList.add(file);}File[] files = fileList.toArray(new File[fileList.size()]);// --打包zipFile(files, "", zos);zos.flush();zos.close();}
/** * 打包檔案 * * @param subs * 檔案數組 * @param baseName * 自訂名字 * @param zos * 輸出資料流 * @throws IOException */private void zipFile(File[] subs, String baseName, ZipOutputStream zos)throws IOException {for (int i = 0; i < subs.length; i++) {File f = subs[i];zos.putNextEntry(new ZipEntry(baseName + f.getName()));FileInputStream fis = new FileInputStream(f);byte[] buffer = new byte[1024];int r = 0;while ((r = fis.read(buffer)) != -1) {zos.write(buffer, 0, r);}fis.close();}}/** * 壓縮包名字 * * @return */private String getZipFilename() {Date date = new Date();String s = date.getTime() + ".zip";return s;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
java基礎入門-ZipOutputStream打包下載