就這個工具類,使用ZipUtil.pack方法進行打包的時候,如果你將要打包的文件是在同一目錄下,不存在分層的情況,那是沒有任何問題的,但是如果存在分層且!!!!文件夾名稱是全中文的時候,就會存在一些問題,具體表現形式是 某些解壓軟件可以正常打開 例如winRAR,但是有些軟件不能正常打開 例如360解壓 如圖
源文件
通過工具類打包過後 winRaR 打開
一切正常 非常完美。 但是用360壓縮打開。。。
如圖 文件夾變成 空白文件了,且解壓報錯。
具體原因是 該工具類底層源碼使用File.list()方法獲取源文件夾所有文件的名稱,在進行copy(打包)過程時,如果判斷當前文件(舉例 假設當前文件是 A )是文件夾時會進行創建文件夾動作,這步存在問題,如果文件A下面沒有文件,這樣寫沒問題,如果文件A下存在文件,那這一步就是多餘的,因爲在copy文件A下的文件的時候 會默認創建出父級目錄,這樣就會產生創建兩次的操作,在文件A名稱是中文名的情況下,會產生問題,導致部分解壓工作不能正確解壓。
所以該工具類存在問題,只能自己封裝了,好在zip打包並不複雜,最底層是使用ZipOutputStream類,寫出來簡簡單單。
附上自己代碼 ,各位可以按照自己業務需求自己魔改一下:
/** * Zip 打包 * @throws IOException */ public static void zipPack(String source,String target)throws IOException { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target)); File file =new File(source); File[] oldFile =file.listFiles(); FileInputStream inputStream; for (int i = 0; i <oldFile.length ; i++) { if (oldFile[i].listFiles()!=null){ for (File f: oldFile[i].listFiles()) { out.putNextEntry(new ZipEntry(oldFile[i].getName()+"/"+f.getName())); byte[] buffer = new byte[4096]; int readLength; inputStream=new FileInputStream(f); while ((readLength = inputStream.read(buffer)) > 0) { byte[] bytes = new byte[readLength]; System.arraycopy(buffer, 0, bytes, 0, readLength); out.write(bytes); } out.closeEntry(); } }else { out.putNextEntry(new ZipEntry(oldFile[i].getName())); byte[] buffer = new byte[4096]; int readLength; inputStream=new FileInputStream(oldFile[i]); while ((readLength = inputStream.read(buffer)) > 0) { byte[] bytes = new byte[readLength]; System.arraycopy(buffer, 0, bytes, 0, readLength); out.write(bytes); } out.closeEntry(); } } out.close(); }