1. 程式人生 > >Android zip檔案解壓縮工具類

Android zip檔案解壓縮工具類

今天專案提了一個新需求:把html網頁放在本地,如果後臺修改了網頁,手機端要去後臺下載壓縮包並解壓後把本地的網頁跟新成最新的,請求後臺介面,根據返回的結果中的某個欄位判斷是否需要下載zip檔案,如果需要下載,返回的結果中會提供zip檔案下載的地址,下載後並解壓顯示網頁,既然需求提了就得去實現

先來看下實現的效果圖:

檔案下載

解壓後顯示本地HTML:

1.實現檔案的下載

2.檔案解壓縮的工具類:

/**
 * Created by YuShuangPing on 2018/11/11.
 */
public class ZipUtils {
    public static final String TAG = "ZIP";

    public ZipUtils() {

    }

    /**
     * 解壓zip到指定的路徑
     *
     * @param zipFileString ZIP的名稱
     * @param outPathString 要解壓縮路徑
     * @throws Exception
     */
    public static void UnZipFolder(String zipFileString, String outPathString) throws Exception {
        ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));
        ZipEntry zipEntry;
        String szName = "";
        while ((zipEntry = inZip.getNextEntry()) != null) {
            szName = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                //獲取部件的資料夾名
                szName = szName.substring(0, szName.length() - 1);
                File folder = new File(outPathString + File.separator + szName);
                folder.mkdirs();
            } else {
                Log.e(TAG, outPathString + File.separator + szName);
                File file = new File(outPathString + File.separator + szName);
                if (!file.exists()) {
                    Log.e(TAG, "Create the file:" + outPathString + File.separator + szName);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                // 獲取檔案的輸出流
                FileOutputStream out = new FileOutputStream(file);
                int len;
                byte[] buffer = new byte[1024];
                // 讀取(位元組)位元組到緩衝區
                while ((len = inZip.read(buffer)) != -1) {
                    // 從緩衝區(0)位置寫入(位元組)位元組
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        }
        inZip.close();
    }

    public static void UnZipFolder(String zipFileString, String outPathString, String szName) throws Exception {
        ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));
        ZipEntry zipEntry;
        while ((zipEntry = inZip.getNextEntry()) != null) {
            //szName = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                //獲取部件的資料夾名
                szName = szName.substring(0, szName.length() - 1);
                File folder = new File(outPathString + File.separator + szName);
                folder.mkdirs();
            } else {
                Log.e(TAG, outPathString + File.separator + szName);
                File file = new File(outPathString + File.separator + szName);
                if (!file.exists()) {
                    Log.e(TAG, "Create the file:" + outPathString + File.separator + szName);
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
                // 獲取檔案的輸出流
                FileOutputStream out = new FileOutputStream(file);
                int len;
                byte[] buffer = new byte[1024];
                // 讀取(位元組)位元組到緩衝區
                while ((len = inZip.read(buffer)) != -1) {
                    // 從緩衝區(0)位置寫入(位元組)位元組
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.close();
            }
        }
        inZip.close();
    }

    /**
     * 壓縮檔案和資料夾
     *
     * @param srcFileString 要壓縮的檔案或資料夾
     * @param zipFileString 解壓完成的Zip路徑
     * @throws Exception
     */
    public static void ZipFolder(String srcFileString, String zipFileString) throws Exception {
        //建立ZIP
        ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
        //建立檔案
        File file = new File(srcFileString);
        //壓縮
        LogUtils.LOGE("---->"+file.getParent()+"==="+file.getAbsolutePath());
        ZipFiles(file.getParent()+ File.separator, file.getName(), outZip);
        //完成和關閉
        outZip.finish();
        outZip.close();
    }

    /**
     * 壓縮檔案
     *
     * @param folderString
     * @param fileString
     * @param zipOutputSteam
     * @throws Exception
     */
    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
        LogUtils.LOGE("folderString:" + folderString + "\n" +
                "fileString:" + fileString + "\n==========================");
        if (zipOutputSteam == null)
            return;
        File file = new File(folderString + fileString);
        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(fileString);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;
            byte[] buffer = new byte[4096];
            while ((len = inputStream.read(buffer)) != -1) {
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        } else {
            //資料夾
            String fileList[] = file.list();
            //沒有子檔案和壓縮
            if (fileList.length <= 0) {
                ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
            }
            //子檔案和遞迴
            for (int i = 0; i < fileList.length; i++) {
                ZipFiles(folderString+fileString+"/",  fileList[i], zipOutputSteam);
            }
        }
    }

    /**
     * 返回zip的檔案輸入流
     *
     * @param zipFileString zip的名稱
     * @param fileString    ZIP的檔名
     * @return InputStream
     * @throws Exception
     */
    public static InputStream UpZip(String zipFileString, String fileString) throws Exception {
        ZipFile zipFile = new ZipFile(zipFileString);
        ZipEntry zipEntry = zipFile.getEntry(fileString);
        return zipFile.getInputStream(zipEntry);
    }

    /**
     * 返回ZIP中的檔案列表(檔案和資料夾)
     *
     * @param zipFileString  ZIP的名稱
     * @param bContainFolder 是否包含資料夾
     * @param bContainFile   是否包含檔案
     * @return
     * @throws Exception
     */
    public static List<File> GetFileList(String zipFileString, boolean bContainFolder, boolean bContainFile) throws Exception {
        List<File> fileList = new ArrayList<File>();
        ZipInputStream inZip = new ZipInputStream(new FileInputStream(zipFileString));
        ZipEntry zipEntry;
        String szName = "";
        while ((zipEntry = inZip.getNextEntry()) != null) {
            szName = zipEntry.getName();
            if (zipEntry.isDirectory()) {
                // 獲取部件的資料夾名
                szName = szName.substring(0, szName.length() - 1);
                File folder = new File(szName);
                if (bContainFolder) {
                    fileList.add(folder);
                }
            } else {
                File file = new File(szName);
                if (bContainFile) {
                    fileList.add(file);
                }
            }
        }
        inZip.close();
        return fileList;
    }
}

3.activity中實現下載解壓顯示html頁面

public class MainActivity extends BaseActivity implements LoginContract.View {
..........
private String savePath = FileUtils.getFileDir() + "thinkyun" + File.separator + "download.zip";//下載檔案的儲存絕對路徑
    private String unZipPath = FileUtils.getFileDir() + "thinkyun" + File.separator + "download";//解壓的zip檔案路徑
..........

 //請求網路成功的返回
    @Override
    public void onLoginSuccess(LoginUserBean2 bean) {
        int update = bean.getUpdate();
        //zip壓縮包的下載地址
        downloadUrl = bean.getZipurl();
        if (update == 1) {//需要下載新的壓縮包
            File file = new File(savePath);
            if (file.exists()) {
                file.delete();
            }
            //開始下載ZIP壓縮包
            FileDownloadUtils.getInstance().startDownLoadFileSingle(downloadUrl, savePath,
                    new FileDownloadUtils.FileDownLoaderCallBack() {
                        @Override
                        public void downLoadCompleted(BaseDownloadTask task) {
                            LogUtils.LOGD("下載完成========");
                            try {
                                //解壓ZIP壓縮包
                                ZipUtils.UnZipFolder(savePath, unZipPath);
                                File file = new File(unZipPath + "/view/homepage/homepage.html");
                                if (file.exists()) {
                                    tv_progress.setVisibility(View.GONE);
                                    //顯示html網頁
                                    webView.loadUrl("file:" + unZipPath + "/view/homepage/homepage.html");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void downLoadError(BaseDownloadTask task, Throwable e) {

                        }

                        @Override
                        public void downLoadProgress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                            tv_progress.setText("下載進度:" + soFarBytes + "/" + totalBytes);
                        }
                    });
        }


    }

..........

}

到此就完成了上述功能