轉自:https://www.cnblogs.com/zeng1994/p/7862288.html 有改動
最近碰到個需要下載zip壓縮包的需求,於是我在網上找了下別人寫好的zip工具類。但找了好多篇博客,總是發現有bug。因此就自己來寫了個工具類。
這個工具類的功能為:
- (1)可以壓縮文件,也可以壓縮文件夾
- (2)同時支持壓縮多級文件夾,工具內部做了遞歸處理
- (3)碰到空的文件夾,也可以壓縮
- (4)可以選擇是否保留原來的目錄結構,如果不保留,所有文件跑壓縮包根目錄去了,且空文件夾直接舍棄。注意:如果不保留文件原來目錄結構,在碰到文件名相同的文件時,會壓縮失敗。
- (5)代碼中提供了2個壓縮文件的方法,一個的輸入參數為文件夾路徑,一個為文件列表,可根據實際需求選擇方法。
下面直接上代碼
一、代碼
ZipUtils
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.OutputStream; 6 import java.util.ArrayList; 7 import java.util.List; 8 import java.util.zip.ZipEntry; 9 import java.util.zip.ZipOutputStream; 10 /** 11 * @author Nemo 12 * @version 1.0 13 * @date 2019/11/5 14 */ 15 public class ZipUtils { 16 private static final int BUFFER_SIZE = 2 * 1024; 17 /** 18 * 壓縮成ZIP 方法1 19 * @param sourceFile 壓縮文件夾路徑 20 * @param out 壓縮文件輸出流 21 * @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構; 22 * false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗) 23 * @throws RuntimeException 壓縮失敗會拋出運行時異常 24 */ 25 public static void toZip(File sourceFile, OutputStream out, boolean KeepDirStructure) 26 throws RuntimeException{ 27 ZipOutputStream zos = null ; 28 try { 29 zos = new ZipOutputStream(out); 30 compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure); 31 } catch (Exception e) { 32 throw new RuntimeException("zip error from ZipUtils",e); 33 }finally{ 34 if(zos != null){ 35 try { 36 zos.close(); 37 } catch (IOException e) { 38 e.printStackTrace(); 39 } 40 } 41 } 42 } 43 /** 44 * 壓縮成ZIP 方法2 45 * @param srcFiles 需要壓縮的文件列表 46 * @param out 壓縮文件輸出流 47 * @throws RuntimeException 壓縮失敗會拋出運行時異常 48 */ 49 public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException { 50 long start = System.currentTimeMillis(); 51 ZipOutputStream zos = null ; 52 try { 53 zos = new ZipOutputStream(out); 54 for (File srcFile : srcFiles) { 55 byte[] buf = new byte[BUFFER_SIZE]; 56 zos.putNextEntry(new ZipEntry(srcFile.getName())); 57 int len; 58 FileInputStream in = new FileInputStream(srcFile); 59 while ((len = in.read(buf)) != -1){ 60 zos.write(buf, 0, len); 61 } 62 zos.closeEntry(); 63 in.close(); 64 } 65 long end = System.currentTimeMillis(); 66 System.out.println("壓縮完成,耗時:" + (end - start) +" ms"); 67 } catch (Exception e) { 68 throw new RuntimeException("zip error from ZipUtils",e); 69 }finally{ 70 if(zos != null){ 71 try { 72 zos.close(); 73 } catch (IOException e) { 74 e.printStackTrace(); 75 } 76 } 77 } 78 } 79 /** 80 * 遞歸壓縮方法 81 * @param sourceFile 源文件 82 * @param zos zip輸出流 83 * @param name 壓縮后的名稱 84 * @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構; 85 * false:所有文件跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名文件,會壓縮失敗) 86 * @throws Exception 87 */ 88 private static void compress(File sourceFile, ZipOutputStream zos, String name, 89 boolean KeepDirStructure) throws Exception{ 90 byte[] buf = new byte[BUFFER_SIZE]; 91 if(sourceFile.isFile()){ 92 // 向zip輸出流中添加一個zip實體,構造器中name為zip實體的文件的名字 93 zos.putNextEntry(new ZipEntry(name)); 94 // copy文件到zip輸出流中 95 int len; 96 FileInputStream in = new FileInputStream(sourceFile); 97 while ((len = in.read(buf)) != -1){ 98 zos.write(buf, 0, len); 99 } 100 // Complete the entry 101 zos.closeEntry(); 102 in.close(); 103 } else { 104 File[] listFiles = sourceFile.listFiles(); 105 if(listFiles == null || listFiles.length == 0){ 106 // 需要保留原來的文件結構時,需要對空文件夾進行處理 107 if(KeepDirStructure){ 108 // 空文件夾的處理 109 zos.putNextEntry(new ZipEntry(name + "/")); 110 // 沒有文件,不需要文件的copy 111 zos.closeEntry(); 112 } 113 }else { 114 for (File file : listFiles) { 115 // 判斷是否需要保留原來的文件結構 116 if (KeepDirStructure) { 117 // 注意:file.getName()前面需要帶上父文件夾的名字加一斜杠, 118 // 不然最后壓縮包中就不能保留原來的文件結構,即:所有文件都跑到壓縮包根目錄下了 119 compress(file, zos, name + "/" + file.getName(),KeepDirStructure); 120 } else { 121 compress(file, zos, file.getName(),KeepDirStructure); 122 } 123 } 124 } 125 } 126 } 127 public static void main(String[] args) throws Exception { 128 /** 測試壓縮方法1 */ 129 FileOutputStream fos1 = new FileOutputStream(new File("c:/mytest01.zip")); 130 ZipUtils.toZip(new File("D:/log"), fos1,true); 131 /** 測試壓縮方法2 */ 132 List<File> fileList = new ArrayList<>(); 133 fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/jar.exe")); 134 fileList.add(new File("D:/Java/jdk1.7.0_45_64bit/bin/java.exe")); 135 FileOutputStream fos2 = new FileOutputStream(new File("c:/mytest02.zip")); 136 ZipUtils.toZip(fileList, fos2); 137 } 138 }
二、注意事項
寫該工具類時,有些注意事項說一下:
(1)支持選擇是否保留原來的文件目錄結構,如果不保留,那么空文件夾直接不用處理。
(1)碰到空文件夾時,如果需要保留目錄結構,則直接添加個ZipEntry就可以了,不過就是這個entry的名字后面需要帶上一斜杠(/)表示這個是目錄。
(2)遞歸時,不需要把zip輸出流關閉,zip輸出流的關閉應該是在調用完遞歸方法后面關閉
(3)遞歸時,如果是個文件夾且需要保留目錄結構,那么在調用方法壓縮他的子文件時,需要把文件夾的名字加一斜杠給添加到子文件名字前面,這樣壓縮后才有多級目錄
三、如何在javaWeb項目中使用該工具類
代碼中的步驟為:
1. 獲取到存在數據庫中的圖片的url
2. 創建要壓縮的文件夾
3. 根據獲取到的圖片的url,把圖片按照想要的文件夾目錄進行下載
4. 把要壓縮的文件夾路徑、壓縮文件輸出流傳入到ZipUtils.toZip方法,對文件夾進行壓縮
5. 刪除壓縮前准備的中間文件
因為接口是GET請求,所以直接拼接接口路由+參數,用瀏覽器打開就能彈出下載。
1 import org.apache.commons.io.FileUtils; 2 import java.io.*; 3 4 /** 5 * 圖片打包下載 6 * @author: wangzhouchao 7 */ 8 @ApiImplicitParams({ 9 @ApiImplicitParam(name = "id", value = "申請人id", required = true, dataType = "Long", paramType = "query"), 10 }) 11 @ApiOperation(value = "圖片打包下載", notes = "圖片打包下載") 12 @RequestMapping(value = "/downloadPictureList", method = RequestMethod.GET) 13 public void downloadPictureList(TProposerDataVO tProposerDataVO) { 14 15 long readyStart = System.currentTimeMillis(); 16 17 // ************* 1. 獲取到存在數據庫中的圖片的url ************* 18 PictureDownloadVO picturesById = tOrderService.getPicturesByProposerDataId(tProposerDataVO.getId()); 19 20 // 獲取當前類的所在項目路徑 21 File file = null; 22 try { 23 file = new File(ResourceUtils.getURL("classpath:").getPath()); 24 } catch (FileNotFoundException e) { 25 throw new RuntimeException("獲取根目錄失敗,無法獲取文件目錄!"); 26 } 27 if(!file.exists()) { 28 file = new File(""); 29 } 30 String absolutePath = file.getAbsolutePath(); 31 32 33 // 要打包的文件夾列表 34 String order_number = picturesById.getOrder_number(); 35 String country_name = picturesById.getCountry_name(); 36 String visa_type = picturesById.getVisa_type(); 37 String dirName = order_number + country_name + visa_type; 38 39 // ************* 2. 創建要壓縮的文件夾 ************* 40 // 根據訂單號+國家名稱+簽證類型創建文件夾 41 File dirOfOrder = new File(absolutePath, dirName); 42 if(!dirOfOrder.exists()) { 43 dirOfOrder.mkdirs(); 44 } 45 46 ZipOutputStream zos = null; 47 OutputStream out = null; 48 49 long readyEnd = System.currentTimeMillis(); 50 System.out.println("准備完成,耗時:" + (readyEnd - readyStart) + " ms"); 51 try { 52 53 long downStart = System.currentTimeMillis(); 54 55 56 System.out.println("開始下載"); 57 58 TProposerDataVO vo = picturesById.getProposerDataVO(); 59 60 // ************* 3. 根據獲取到的圖片的url,把圖片按照想要的文件夾目錄進行下載 ************* 61 // 根據申請人姓名創建文件夾 62 File proposerFile = new File(dirOfOrder, vo.getReal_name()); 63 if (!proposerFile.exists()) { 64 proposerFile.mkdirs(); 65 } 66 // 下載申請人照片 67 if (StringUtil.checkNotNull(vo.getPhoto_url())) { 68 System.out.println("開始下載申請人照片"); 69 WordExportUtil.downloadHttpUrl(DOMAIN + vo.getPhoto_url(), proposerFile.toString(), File.separator + "photo.jpg"); 70 } 71 // 下載申請人護照首頁 72 if (StringUtil.checkNotNull(vo.getPassport_home_page_url())) { 73 System.out.println("開始下載申請人護照照片"); 74 WordExportUtil.downloadHttpUrl(DOMAIN + vo.getPassport_home_page_url(), proposerFile.toString(), File.separator + "passport.jpg"); 75 } 76 // 下載申請人戶口本照片 77 if (StringUtil.checkNotNull(vo.getResidence_booklet_url())) { 78 System.out.println("開始下載申請人戶口本照片"); 79 String[] booklets = vo.getResidence_booklet_url().split(","); 80 // 創建戶口本照片文件夾 81 File bookletsFile = new File(proposerFile, "hukouben"); 82 if (!bookletsFile.exists()) { 83 bookletsFile.mkdirs(); 84 } 85 for (int k = 0; k < booklets.length; k++) { 86 WordExportUtil.downloadHttpUrl(DOMAIN + booklets[k], bookletsFile.toString(), File.separator + "residenceBooklet" + k + ".jpg"); 87 } 88 } 89 // 下載申請人身份證照片 90 if (StringUtil.checkNotNull(vo.getId_card_status()) && vo.getId_card_status() == 0) { 91 System.out.println("開始下載申請人身份證照片"); 92 // 創建身份證照片文件夾 93 File idCards = new File(proposerFile, "idCards"); 94 if (!idCards.exists()) { 95 idCards.mkdirs(); 96 } 97 if (StringUtil.checkNotNull(vo.getId_card_positive_url())) { 98 WordExportUtil.downloadHttpUrl(DOMAIN + vo.getId_card_positive_url(), idCards.toString(), File.separator + "idCardPostive.jpg"); 99 } 100 if (StringUtil.checkNotNull(vo.getId_card_reverse_url())) { 101 WordExportUtil.downloadHttpUrl(DOMAIN + vo.getId_card_reverse_url(), idCards.toString(), File.separator + "idCardReverse.jpg"); 102 } 103 } 104 // 下載申請人婚姻證明照片 105 if (StringUtil.checkNotNull(vo.getMar_div_card_url())) { 106 System.out.println("開始下載申請人婚姻證明照片"); 107 WordExportUtil.downloadHttpUrl(DOMAIN + vo.getMar_div_card_url(), proposerFile.toString(), File.separator + "marriage.jpg"); 108 } 109 // 下載申請人輔助資產照片 110 if (StringUtil.checkNotNull(vo.getAuxiliary_assets_url())) { 111 System.out.println("開始下載申請人輔助資產照片"); 112 String[] auxiliarys = vo.getAuxiliary_assets_url().split(","); 113 // 創建輔助資產照片文件夾 114 File auxiliarysFile = new File(proposerFile, "fuzhuzichan"); 115 if (!auxiliarysFile.exists()) { 116 auxiliarysFile.mkdirs(); 117 } 118 for (int k = 0; k < auxiliarys.length; k++) { 119 WordExportUtil.downloadHttpUrl(DOMAIN + auxiliarys[k], auxiliarysFile.toString(), File.separator + "auxiliary" + k + ".jpg"); 120 } 121 } 122 // 下載申請人居住證照片 123 if (StringUtil.checkNotNull(vo.getResidence_permit_url())) { 124 System.out.println("開始下載申請人居住證照片"); 125 String[] residences = vo.getResidence_permit_url().split(","); 126 // 創建居住證照片文件夾 127 File residencesFile = new File(proposerFile, "juzhuzheng"); 128 if (!residencesFile.exists()) { 129 residencesFile.mkdirs(); 130 } 131 for (int k = 0; k < residences.length; k++) { 132 WordExportUtil.downloadHttpUrl(DOMAIN + residences[k], residencesFile.toString(), File.separator + "residence" + k + ".jpg"); 133 } 134 } 135 // 下載申請人其余補充資料照片 136 if (StringUtil.checkNotNull(vo.getOther_data_url())) { 137 System.out.println("開始下載申請人其余補充資料照片"); 138 String[] others = vo.getOther_data_url().split(","); 139 // 創建其余補充資料照片文件夾 140 File othersFile = new File(proposerFile, "qitabuchongziliao"); 141 if (!othersFile.exists()) { 142 othersFile.mkdirs(); 143 } 144 for (int k = 0; k < others.length; k++) { 145 WordExportUtil.downloadHttpUrl(DOMAIN + others[k], othersFile.toString(), File.separator + "other" + k + ".jpg"); 146 } 147 } 148 // 下載申請人證明資料照片 149 if (StringUtil.checkNotNull(vo.getProve_url())) { 150 System.out.println("開始下載申請人證明資料照片"); 151 String[] prove_urls = vo.getProve_url().split(","); 152 // 創建證明資料照片文件夾 153 File proveFile = new File(proposerFile, "zhengmingziliao"); 154 if (!proveFile.exists()) { 155 proveFile.mkdirs(); 156 } 157 for (int k = 0; k < prove_urls.length; k++) { 158 WordExportUtil.downloadHttpUrl(DOMAIN + prove_urls[k], proveFile.toString(), File.separator + "prove" + k + ".jpg"); 159 } 160 } 161 162 long downEnd = System.currentTimeMillis(); 163 System.out.println("下載完成,耗時:" + (downEnd - downStart) + " ms"); 164 long zipStart = System.currentTimeMillis(); 165 166 response.setContentType("application/x-zip-compressed"); 167 response.setHeader("Content-disposition", "attachment;filename=" + StringUtil.getUUID() + ".zip"); 168 out = response.getOutputStream(); 169 zos = new ZipOutputStream(out); 170 171 // ************* 4. 把要壓縮的文件夾路徑、壓縮文件輸出流傳入到ZipUtils.toZip方法,對文件夾進行壓縮 ************* 172 // 對文件夾進行壓縮,保留原文件夾路徑 173 ZipUtils.toZip(dirOfOrder, out, true); 174 long zipEnd = System.currentTimeMillis(); 175 System.out.println("壓縮完成,耗時:" + (zipEnd - zipStart) + " ms"); 176 177 out.flush(); 178 } catch (IOException e) { 179 e.printStackTrace(); 180 } catch (Exception e) { 181 throw new RuntimeException("zip error from ZipUtils", e); 182 } finally { 183 if (zos != null) { 184 try { 185 zos.close(); 186 } catch (IOException e) { 187 e.printStackTrace(); 188 } 189 } 190 if (out != null) { 191 try { 192 zos.close(); 193 out.close(); 194 } catch (IOException e) { 195 e.printStackTrace(); 196 } 197 } 198 } 199 200 // ************* 5. 刪除壓縮前准備的中間文件 ************* 201 if (dirOfOrder != null) { 202 try { 203 FileUtils.deleteDirectory(dirOfOrder); 204 System.out.println("中間文件已刪除"); 205 } catch (IOException e) { 206 e.printStackTrace(); 207 System.out.println("中間文件刪除失敗"); 208 } 209 } 210 }