zoukankan      html  css  js  c++  java
  • Android 下载zip压缩文件并解压

    网上有很多介绍下载文件或者解压zip文件的文章,但是两者结合的不多,在此记录一下下载zip文件并直接解压的方法。

    其实也很简单,就是把下载文件和解压zip文件结合到一起。下面即代码:

            URLConnection connection;  
            ZipInputStream zipIn = null;
            FileOutputStream fileOut = null;
            ZipEntry zipEntry = null;
            int readedBytes = 0;
            try {
                connection = modelUrl.openConnection();
                Log.v(TAG, "model file length:"+connection.getContentLength());
                zipIn = new ZipInputStream(connection.getInputStream());
                while ((zipEntry = zipIn.getNextEntry()) != null) {
                    String entryName = zipEntry.getName();
                    if (zipEntry.isDirectory()) {
                        entryName = entryName.substring(0, entryName.length() - 1);
                        File folder = new File(folderPath + File.separator+ entryName);
                        folder.mkdirs();
                    } else {
                        String fileName=folderPath + File.separator + entryName;
                        File file = new File(fileName);
                        file.createNewFile();
                        fileOut = new FileOutputStream(file);
                        while ((readedBytes = zipIn.read(downLoadBuffer)) > 0) {
                            fileOut.write(downLoadBuffer, 0, readedBytes);
                            total+=readedBytes;
                        }
                        fileOut.close();
                    }
                    zipIn.closeEntry();
                }
                zipIn.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

     更新

    在此处其实有一个坑,如果downLoadBuffer这个缓冲区设置的太大,会导致下载的文件总是不完整或者抛出异常下载失败。我在网上搜了一下,没有找到原因。经过我的测试,原因应该是:下载和解压是两个步骤,一般来说解压的速度都高于下载,当下载的数据比解压需要的数据少太多时(即两者速度不匹配),就会出现下载文件失败的情况。因此,需要把downLoadBuffer设置的小一点,控制解压速度,即每次只解压一小部分的数据,这样两者的速度才能比较匹配。我的代码中设置成了1024*8,共8kb。保守的做法是设置成1024,即1kb,一般都不会出问题。

  • 相关阅读:
    django admin site配置(二)
    MyEclipse中无法将SVN检出来的项目部署到tomcat中
    遍历目录树,清理编译目录
    axis2学习, ant 构建axis2 ws
    [置顶] 2013 Multi-University Training Contest 8
    Cocos2d-x 关于在iOS平台真机测试的一些注意
    SharePoint 2013的100个新功能之社交
    路由共享上网原理
    red ant
    nginx正向代理访问百度地图API
  • 原文地址:https://www.cnblogs.com/hrlnw/p/4211328.html
Copyright © 2011-2022 走看看