Android解压中文乱码
16lz
2021-01-24
在Android中内置有解压的工具,一般可以使用下面的方法解压:
�注意import的包:
因
import java.util.zip.ZipEntry;import java.util.zip.ZipFile;/** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 * @throws IOException 当解压缩过程出错时抛出 */ public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = new ZipFile(zipFile); for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); InputStream in = zf.getInputStream(entry); if(entry.getName().indexOf("__MACOSX")>=0){ continue; } String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("8859_1"), "UTF-8"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buffer)) > 0) { out.write(buffer, 0, realLength); } in.close(); out.close(); } }
但是在解压遇到中文的时候,解压出来中文会变成乱码,把上面的编码改成啥都没用。
果
这时候可以使用apache-ant-zip的解压包来解决:
- 先将apache-ant-zip.jar加入依赖,下载地址:http://download.csdn.net/detail/qq_25806863/9878967
然后使用这个包中的引用:
import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;public static void upZipFile(File zipFile, String folderPath) throws IOException { OutputStream os = null; InputStream is = null; ZipFile zf = null; try { zf = new ZipFile(zipFile,"UTF-8"); String directoryPath = ""; directoryPath = folderPath; Enumeration entryEnum = zf.getEntries(); if (null != entryEnum) { ZipEntry zipEntry = null; while (entryEnum.hasMoreElements()) { zipEntry = (ZipEntry) entryEnum.nextElement(); if (zipEntry.isDirectory()) { //不处理文件夹 directoryPath = directoryPath + File.separator + zipEntry.getName(); System.out.println(directoryPath); continue; } if (zipEntry.getSize() > 0) { File targetFile = new File(directoryPath+ File.separator + zipEntry.getName()); if (!targetFile.exists()) { //如果不存在就创建 File fileParentDir = targetFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } targetFile.createNewFile(); } os = new BufferedOutputStream(new FileOutputStream(targetFile)); is = zf.getInputStream(zipEntry); byte[] buffer = new byte[4096]; int readLen = 0; while ((readLen = is.read(buffer, 0, 1024)) >= 0) { os.write(buffer, 0, readLen); } os.flush(); os.close(); } } } } catch (IOException ex) { throw ex; } finally { if (null != is) { is.close(); } if (null != os) { os.close(); } } }
更多相关文章
- Android基于名称、修改时间、大小实现文件夹排序
- android中保存Bitmap图片到指定文件夹中的方法
- ADT+Maven Android(安卓)App开发配置备忘
- Android(安卓)中文 API (23) —— MultiAutoCompleteTextView.Toke
- Android下载及安装
- Android(安卓)TextView设置中文粗体
- [Android(安卓)Studio]添加选项菜单
- android之本地文件读取
- Android——Jni使用总结