Android 解壓zip檔案(支援中文)
阿新 • • 發佈:2018-12-30
PS:用於解壓縮 Google Play 上面下載下來的 obb 擴充套件檔案!
過了n多天後,當再次使用原先部落格上寫的那篇:
去做zip包的解壓的時候,出現了原來沒有發現的很多問題。首先是中文漢字問題,使用java的zip包不能很好的解決解壓問題;其次還有
getRealFileName()內的那個判斷:
由之前的"if(dirs.length >1)" 如果是 >1 的話,對於一些檔案不能夠解壓,修改為:
if(dirs.length>0)
對於zip壓縮包內包含中文目錄或者中文檔案的話,參考網上的資源:
“使用apache的zip工具包(所在包為ant.jar )代替JDK的zip工具包,因為java型別自帶的不支援中文路徑,不過兩者使用的方式是一樣的,只是apache壓縮工具多了設定編碼方式的介面,其他基本上是一樣的。”
如果android下想使用 apache 需要匯入 ant.jar 這個包,下面附上下載連結:
http://download.csdn.net/detail/shizhending/4139787
對於android 工程新增 jar 包的方法也提供一下入口吧:
http://hi.baidu.com/yore2003/item/fb6d5cd21a4bec4dddf9bef2
上面講到的新增 jar 要注意下最好是:
右鍵工程->properties->Java Build Path->Order and Export
然後把剛才加的 Libray jar 置頂。
下面是使用apache zip工具包的具體原始碼:
同樣記得要在AndroidManifest.xml裡新增許可權。public static void unZipFile(String archive, String decompressDir)throws IOException, FileNotFoundException, ZipException { BufferedInputStream bi; ZipFile zf = new ZipFile(archive, "GBK"); Enumeration e = zf.getEntries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); String entryName = ze2.getName(); String path = decompressDir + "/" + entryName; if (ze2.isDirectory()) { System.out.println("正在建立解壓目錄 - " + entryName); File decompressDirFile = new File(path); if (!decompressDirFile.exists()) { decompressDirFile.mkdirs(); } } else { System.out.println("正在建立解壓檔案 - " + entryName); String fileDir = path.substring(0, path.lastIndexOf("/")); File fileDirFile = new File(fileDir); if (!fileDirFile.exists()) { fileDirFile.mkdirs(); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir + "/" + entryName)); bi = new BufferedInputStream(zf.getInputStream(ze2)); byte[] readContent = new byte[1024]; int readCount = bi.read(readContent); while (readCount != -1) { bos.write(readContent, 0, readCount); readCount = bi.read(readContent); } bos.close(); } } zf.close(); //bIsUnzipFinsh = true; }