Android(安卓)unZip
16lz
2021-01-26
坑点
1. 使用java自带的 java.util.zip , 不支持中文文件名,文件名是乱码。
2. 使用 ZipInputStream 文件名不能有空格,否则解码错误。
3. 使用 org.apache.tools.zip, 可解决1,2问题, 但文件zip.getEntries() 文件顺序由点乱。
使用 org.apache.tools.zip 的代码如下:
public static boolean unZip(final File zipFile, final File destDir) { if(null == zipFile || null == destDir) { return false; } ZipFile zip = null; try { zip = new ZipFile(zipFile, "GBK"); } catch (IOException e1) { e1.printStackTrace(); LogMessageMgr.i(TAG, "new Zip Exception:" + e1.getMessage()); return false; } Enumeration<?> entries = zip.getEntries(); byte[] buffer = new byte[1024]; String sWriteExceptionMsg = ""; while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String entryName = entry.getName(); File file = new File(destDir.getPath() + File.separator + entryName); if(entry.isDirectory()){ if(!file.exists()){ file.mkdirs(); } }else{ if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } InputStream is = null; FileOutputStream os = null; try{ is = zip.getInputStream(entry); os = new FileOutputStream(file); if(file.getPath().toLowerCase().endsWith(".txt")){ int readLen = is.read(buffer); if(readLen > 0){//过滤掉UTF-8格式文本 bom 字符 if( buffer[0] == (byte)0xef && buffer[1] == (byte)0xbb && buffer[2] == (byte)0xbf ){ os.write(buffer, 3, readLen); }else{ os.write(buffer, 0, readLen); } } } while(true){ int readLen = is.read(buffer); if(readLen > 0){ os.write(buffer, 0, readLen); }else{ break; } } } catch (FileNotFoundException e) { sWriteExceptionMsg = e.getMessage(); break; } catch (Exception e) { sWriteExceptionMsg = e.getMessage(); break; } finally{ try { if(null != os){ os.close(); } if(null != is){ is.close(); } } catch (IOException e) { e.printStackTrace(); sWriteExceptionMsg = e.getMessage(); break; } } } } try { zip.close(); } catch (IOException e) { e.printStackTrace(); } if(TextUtils.isEmpty(sWriteExceptionMsg)){ return true; }else{ LogMessageMgr.i(TAG, "unZip Exception:" + sWriteExceptionMsg); return false; } }
更多相关文章
- NDK使用log的问题
- Android(安卓)热修复 技术浅析
- Android(安卓)Studio 将module打成jar包
- Android新控件MotionLayout介绍(一)
- Android(安卓)- 文件操作 小结
- android 系统定制之编译方法总结
- Android(安卓)Studio 使用技巧集锦
- java化改造--xml布局文件转成java——学习整理
- Android(安卓)SDK Manager 和 ADT 更新