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

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();
      
    }

猜你喜欢

转载自blog.csdn.net/langxian_168/article/details/80322865
今日推荐