Android读取assets文件夹并解压到内存卡中

该方法演示了如何在Android应用中从assets文件夹读取zip文件,并将其解压缩到设备的外部存储。首先,创建目标解压目录,然后通过AssetManager打开zip文件,使用ZipInputStream遍历并解压每个文件。如果遇到目录则创建,如果是文件则写入到指定位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public  void unZip( String assetName, String savefilename) throws IOException {
        // 创建解压目标目录
        File file = new File(savefilename);
        // 如果目标目录不存在,则创建
        if (!file.exists()) {
            file.mkdirs();
        }
       
        InputStream inputStream = getAssets().open(assetName);
//      inputStream =getClass().getResourceAsStream(assetName;//也可以进行流解读
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        // 读取一个进入点
        ZipEntry nextEntry = zipInputStream.getNextEntry();
        byte[] buffer = new byte[1024 * 1024];
        int count = 0;
        // 如果进入点为空说明已经遍历完所有压缩包中文件和目录
        while (nextEntry != null) {
            // 如果是一个文件夹
            if (nextEntry.isDirectory()) {
                file = new File(savefilename + File.separator + nextEntry.getName());
               if (  !file.exists()) {
                    file.mkdir();
                }
            } else {
                // 如果是文件那就保存
                file = new File(savefilename + File.separator + nextEntry.getName());
                // 则解压文件
                if ( !file.exists()) {
                    file.createNewFile();
                    FileOutputStream fos = new FileOutputStream(file);
                    while ((count = zipInputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, count);
                    }
              
                  fos.close();
                }
            }
           
            //这里很关键循环解读下一个文件
            nextEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
      
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值