Android 解压文件

解压文件无非就是这几个步骤:

1.指定要解压文件的位置和解压后文件或是文件夹的位置

2.列出压缩文件中所有的文件或是文件夹

3.如果是文件,则读取。如果是文件夹,则创建。

以下为实例代码:

public static void unzip(String zipFilePath, String targetPath)
        throws IOException {
    OutputStream os = null;
    InputStream is = null;
    ZipFile zipFile = null;
    try {
        //1.获取要解压的文件 , 并指定解压格式为“GBK”
        zipFile = new ZipFile(zipFilePath, Charset.forName("GBK"));
        //读取zip文件中每一个文件及文件夹
        Enumeration<?> entryEnum = zipFile.entries();
        if (null != entryEnum) {
            ZipEntry zipEntry = null;
            //总共有多少文件或是文件夹就循环多少次
            while (entryEnum.hasMoreElements()) {
                //获取下一个文件或者文件夹
                zipEntry = (ZipEntry) entryEnum.nextElement();
                if (zipEntry.getSize() > 0) {
                    // 文件  File.separator就是“/”
                    File targetFile = new File(targetPath
                            + File.separator + zipEntry.getName());
                    //将文件读取到指定文件位置
                    os = new BufferedOutputStream(new FileOutputStream(targetFile));
                    is = zipFile.getInputStream(zipEntry);
                    byte[] buffer = new byte[4096];
                    int readLen = 0;
                    while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
                        os.write(buffer, 0, readLen);
                        os.flush();
                    }
                    is.close();
                    os.close();
                }
                //如果是文件夹,则创建文件夹
                if (zipEntry.isDirectory()) {
                    String pathTemp = targetPath + File.separator
                            + zipEntry.getName();
                    File file = new File(pathTemp);
                    file.mkdirs();
                }
            }
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        //关闭流
        if (null != zipFile) {
            zipFile.close();
            zipFile = null;
        }
        if (null != is) {
            is.close();
        }
        if (null != os) {
            os.close();
        }
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值