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,一般都不会出问题。

posted @ 2015-01-08 17:25  handspeaker  阅读(8656)  评论(1编辑  收藏  举报