网上有很多介绍下载文件或者解压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,一般都不会出问题。

更多相关文章

  1. Android(安卓)手机上传图片至javaweb服务器(servlet)
  2. Android2.2快速入门 zz
  3. Androidstudio打包jar和arr包
  4. AndroidStudio 升级后遇到的问题
  5. Android(安卓)6.0 Marshmallow root 方法
  6. Android中Listview通过适配器设置Item的高度及其他样式
  7. Android(安卓)Debug Tools
  8. Android工程中配置OpenCV
  9. Android(安卓)中Odex文件生成与合并

随机推荐

  1. android:屏幕自适应(转)
  2. Android(安卓)客户端起HttpServer NanoHt
  3. [Android] (Android 视频悬浮窗)
  4. Android sdk下载找不到support library
  5. Android设置Settings:PreferenceFragment
  6. Android 响应System UI状态,焦点改变,手势
  7. android 自定义 permission 权限
  8. Ogre3D 1.8.1 Android移植
  9. Android EventBus源码分析
  10. Android M5 新特性