在我们制作 Android 程序的时候,会有一些需求:用户要安装包尽可能的小,同时在打包 apk 的时候还要将可能用到的资源都打包到 apk 中,在尽量把资源打包到 apk 的前提下,我们可以考虑使用压缩来解决。
下面是解压的调用代码:
- InputStream inputStream = new FileInputStream(fileTemp);
- unZip(inputStream, context.getFilesDir().getAbsolutePath() + "/", true);
解压的代码:
测试代码下载
- /**
- * @param inputStream 要解压的文件
- * @param outputDirectory 输出目录
- * @param isReWrite 是否覆盖
- * @throws IOException
- */
- public static void unZip(InputStream inputStream, String outputDirectory, boolean isReWrite) throws IOException {
- // 创建解压目标目录
- File file = new File(outputDirectory);
- // 如果目标目录不存在,则创建
- if (!file.exists()) {
- file.mkdirs();
- }
- // 打开压缩文件
- ZipInputStream zipInputStream = new ZipInputStream(inputStream);
- // 读取一个进入点
- ZipEntry zipEntry = zipInputStream.getNextEntry();
- // 使用 1Mbuffer
- byte[] buffer = new byte[1024];
- // 解压时字节计数
- int count = 0;
- // 如果进入点为空说明已经遍历完所有压缩包中文件和目录
- while (zipEntry != null) {
- // 如果是一个目录
- if (zipEntry.isDirectory()) {
- file = new File(outputDirectory + File.separator + zipEntry.getName());
- // 文件需要覆盖或者是文件不存在
- if (isReWrite || !file.exists()) {
- file.mkdir();
- }
- } else {
- // 如果是文件
- file = new File(outputDirectory + File.separator + zipEntry.getName());
- // 文件需要覆盖或者文件不存在,则解压文件
- if (isReWrite || !file.exists()) {
- file.createNewFile();
- FileOutputStream fileOutputStream = new FileOutputStream(file);
- while ((count = zipInputStream.read(buffer)) > 0) {
- fileOutputStream.write(buffer, 0, count);
- }
- fileOutputStream.close();
- }
- }
- // 定位到下一个文件入口
- zipEntry = zipInputStream.getNextEntry();
- }
- zipInputStream.close();
- }
转载请注明:热爱改变生活.cn » Android 中的文件解压
本博客只要没有注明“转”,那么均为原创。 转载请注明链接:sumile.cn » Android 中的文件解压