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,一般都不會出問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM