Android 下载Zip文件,并解压到本地,进行本地调用

如有不对的地方,望各路大神指点,小女子在此谢过O(∩_∩)O

点击此处下载demo,看完整代码,(*^__^*) 嘻嘻……

 

 

1.下载文件

  /**
     * 下载zip文件
     *
     * @param url
     */
    private void downloadFile(final String url) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS);
        Request request = new Request.Builder().url(url).build();
        builder.build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[4096];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = Tools.isExistDir_html(filePath);
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
//                    File file = new File(savePath, getNameFromUrl(url));
                    File file = new File(savePath, getNameFromUrl(fileName));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中

                    }
                    fos.flush();
                } catch (Exception e) {
                    //
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
                // 下载完成,解压zip
                //下载完成,先删除过时数据,并解压最新的热更新数据(必须这样操作 不然会导致无法覆盖旧数据,导致数据更新失败)
                deleteOldData();
            }
        });
    }

  删除旧数据deleteOldData

   private void deleteOldData() {
        String dirPath = Constants.BLACKTECH_HOT_UPDATE_FILE_PATH;
        List<File> files = CommandUtils.getFilesInDirectory(dirPath);
        for (File file : files) {
            String fileName = file.getName();
            if (fileName.endsWith(Constants.UXUE_TEMP_FILE_SUFFIX)) {
//                String type = fileName.substring(0, fileName.indexOf("_"));
//                CommandUtils.deleteDirectory(dirPath + fileName);
                CommandUtils.deleteDirectory(dirPath);
                try {
                    ZipFileUtil.upZipFile(file, dirPath);
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
//                    Logcat.e("解压文件失败:" + file.getPath());
                }
            }
        }
    }
 /**
     * 获取目录中的所有一级文件(不包括目录和嵌套文件)
     *
     * @param sPath
     * @return
     */
    public static List<File> getFilesInDirectory(String sPath) {
        List<File> result = new ArrayList<>();
        // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return result;
        }
        File[] files = dirFile.listFiles();
        for (File file : files) {
            if (file.isFile()) {
                result.add(file);
            }
        }
        return result;
    }

 

/**
     * 删除目录(文件夹)以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true,否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; files != null && i < files.length; i++) {
            if (files[i].getName().equals("YJHtml.zip")){
                continue;
            }
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }
 /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

 

解压zip

 /**
     * 解压缩功能.
     * 将zipFile文件解压到folderPath目录下.
     *
     * @throws Exception
     */
    public static int upZipFile(File zipFile, String folderPath) throws Exception {
        try {
            ZipFile zfile = new ZipFile(zipFile);
            Enumeration zList = zfile.entries();
            ZipEntry ze = null;
            byte[] buf = new byte[1024];
            while (zList.hasMoreElements()) {
                ze = (ZipEntry) zList.nextElement();
                if (ze.isDirectory()) {
                    //Logcat.d("upZipFile", "ze.getName() = " + ze.getName());
                    String dirstr = folderPath + ze.getName();
                    //dirstr.trim();
                    dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                    //Logcat.d("upZipFile", "str = " + dirstr);
                    File f = new File(dirstr);
                    f.mkdir();
                    continue;
                }
                //Logcat.d("upZipFile", "ze.getName() = " + ze.getName());
                OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
                InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
                int readLen = 0;
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    os.write(buf, 0, readLen);
                }
                is.close();
                os.close();
            }
            zfile.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

 

 

注意:解压时一定要先删除之前本地的文件里的数据,然后再进行解压,不然会导致无法覆盖的情况

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
Android 平台上解压 ZIP 文件,你可以使用以下代码示例: ```java import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipUtils { private static final int BUFFER_SIZE = 4096; public static void unzip(String zipFilePath, String destDirectory) { try { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); } catch (Exception e) { Log.e("ZipUtils", "Error while unzipping file: " + e.getMessage()); } } private static void extractFile(ZipInputStream zipIn, String filePath) { try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); } bos.close(); } catch (Exception e) { Log.e("ZipUtils", "Error while extracting file: " + e.getMessage()); } } } ``` 使用上述代码,你只需调用 `unzip` 方法,传入 ZIP 文件的路径和解压目标目录的路径即可。注意确保你的应用已经获取了文件读写权限。 示例用法: ```java String zipFilePath = "/path/to/your/zip/file.zip"; String destDirectory = "/path/to/your/destination/directory"; ZipUtils.unzip(zipFilePath, destDirectory); ``` 将上述路径替换为你实际的文件路径和目标目录路径。 希望对你有所帮助!如有任何问题,请随时提问。
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值