公司项目有个需求, 需要下载一个HTML文件压缩包到本地 用WebView显示html页面。网上找到了下面链接 修改了一下就可以自己用:

http://blog.csdn.net/hopehe888999/article/details/19035373

我将原方法中的很多东西进行了简化,看起来更简单明了一点。下面直接上代码:

文件下载类

public class DownLoaderTask extends AsyncTask<Void, Integer, Long> {private final String TAG = "DownLoaderTask";private URL mUrl;private File mFile;private int mProgress = 0;private ProgressReportingOutputStream mOutputStream;private Context mContext;private String mTypeStr;// 文件下载的url 保存路径 out
public DownLoaderTask(String url,String out,Context context,String typeStr){super();if(context!=null){mContext = context;mTypeStr=typeStr;}try {mUrl = new URL(url);String fileName = new File(mUrl.getFile()).getName();mFile = new File(out, fileName);Log.d(TAG, "out="+out+", name="+fileName+",mUrl.getFile()="+mUrl.getFile());} catch (MalformedURLException e) {e.printStackTrace();}}@Overrideprotected void onPreExecute() {// TODO Auto-generated method stub}@Overrideprotected Long doInBackground(Void... params) {// TODO Auto-generated method stubreturn download();}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stub}//下载保存后执行@Overrideprotected void onPostExecute(Long result) {// TODO Auto-generated method stubif(isCancelled())return;//解压ZipExtractorTask task = new ZipExtractorTask(Constants.SAVE_FILES_PATH+mTypeStr,Constants.SAVE_FILES_PATH, mContext,true);task.execute();}private long download(){URLConnection connection = null;int bytesCopied = 0;try {connection = mUrl.openConnection();int length = connection.getContentLength();if(mFile.exists()&&length == mFile.length()){Log.d(TAG, "file "+mFile.getName()+" already exits!!");return 0l;}mOutputStream = new ProgressReportingOutputStream(mFile);publishProgress(0,length);bytesCopied =copy(connection.getInputStream(),mOutputStream);if(bytesCopied!=length&&length!=-1){Log.e(TAG, "Download incomplete bytesCopied="+bytesCopied+", length"+length);}mOutputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return bytesCopied;}private int copy(InputStream input, OutputStream output){byte[] buffer = new byte[1024*8];BufferedInputStream in = new BufferedInputStream(input, 1024*8);BufferedOutputStream out  = new BufferedOutputStream(output, 1024*8);int count =0,n=0;try {while((n=in.read(buffer, 0, 1024*8))!=-1){out.write(buffer, 0, n);count+=n;}out.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}private final class ProgressReportingOutputStream extends FileOutputStream{public ProgressReportingOutputStream(File file)throws FileNotFoundException {super(file);// TODO Auto-generated constructor stub}@Overridepublic void write(byte[] buffer, int byteOffset, int byteCount)throws IOException {// TODO Auto-generated method stubsuper.write(buffer, byteOffset, byteCount);mProgress += byteCount;publishProgress(mProgress);}}
}

文件解压类 对压缩文件进行解压(上面的类中 已执行解压方法)

/***  解压*/
public class ZipExtractorTask extends AsyncTask<Void, Integer, Long> {private final String TAG = "ZipExtractorTask";private final File mInput;private final File mOutput;
//  private final ProgressDialog mDialog;private int mProgress = 0;private final Context mContext;private boolean mReplaceAll;WebView mWebView;
public ZipExtractorTask(String in, String out, Context context, boolean replaceAll){super();mInput = new File(in);mOutput = new File(out);if(!mOutput.exists()){if(!mOutput.mkdirs()){Log.e(TAG, "Failed to make directories:"+mOutput.getAbsolutePath());}}mContext = context;mReplaceAll = replaceAll;}@Overrideprotected Long doInBackground(Void... params) {// TODO Auto-generated method stubreturn unzip();}@Overrideprotected void onPostExecute(Long result) {// TODO Auto-generated method stub//super.onPostExecute(result);if(isCancelled())return;//这里表示解压完成  可以进行显示WebView 发送广播 并更新保存的 时间Intent intent = new Intent();intent.setAction("com.sl.unzip");mContext.sendBroadcast(intent);}@Overrideprotected void onPreExecute() {// TODO Auto-generated method stub//super.onPreExecute();}@Overrideprotected void onProgressUpdate(Integer... values) {// TODO Auto-generated method stub}private long unzip(){long extractedSize = 0L;Enumeration<ZipEntry> entries;ZipFile zip = null;try {zip = new ZipFile(mInput);long uncompressedSize = getOriginalSize(zip);publishProgress(0, (int) uncompressedSize);entries = (Enumeration<ZipEntry>) zip.entries();while(entries.hasMoreElements()){ZipEntry entry = entries.nextElement();if(entry.isDirectory()){continue;}File destination = new File(mOutput, entry.getName());if(!destination.getParentFile().exists()){Log.e(TAG, "make="+destination.getParentFile().getAbsolutePath());destination.getParentFile().mkdirs();}if(destination.exists()&&mContext!=null&&!mReplaceAll){}ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);extractedSize+=copy(zip.getInputStream(entry),outStream);outStream.close();}} catch (ZipException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {zip.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return extractedSize;}private long getOriginalSize(ZipFile file){Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) file.entries();long originalSize = 0l;while(entries.hasMoreElements()){ZipEntry entry = entries.nextElement();if(entry.getSize()>=0){originalSize+=entry.getSize();}}return originalSize;}private int copy(InputStream input, OutputStream output){byte[] buffer = new byte[1024*8];BufferedInputStream in = new BufferedInputStream(input, 1024*8);BufferedOutputStream out  = new BufferedOutputStream(output, 1024*8);int count =0,n=0;try {while((n=in.read(buffer, 0, 1024*8))!=-1){out.write(buffer, 0, n);count+=n;}out.flush();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return count;}private final class ProgressReportingOutputStream extends FileOutputStream{public ProgressReportingOutputStream(File file)throws FileNotFoundException {super(file);// TODO Auto-generated constructor stub}@Overridepublic void write(byte[] buffer, int byteOffset, int byteCount)throws IOException {// TODO Auto-generated method stubsuper.write(buffer, byteOffset, byteCount);mProgress += byteCount;publishProgress(mProgress);}}
}

我写的这个是下载完成后自动解压到对应的路径。到时候可以根据情况进行修改。最后在子线程中调用执行:

DownLoaderTask downLoaderTask= new DownLoaderTask(Constants.WEB_HTTP_URLZIP+string, Constants.SAVE_FILES_PATH, getActivity(), "/"+zipName );downLoaderTask.execute();

下图为解压成功后的调用

vebView.loadUrl("file:///data/data/com.sl.washshop/wash_doc.html");//加载本地网页 "///"是系统默认的标识

android 下载zip文件并解压相关推荐

  1. android下zip压缩文件加密解密的完美解决方案,Android之zip文件加密解压及进度条的实现...

    zip文件的解压可以使用java的zip库,但是没有实现对加密文件的解压功能,这里可以使用zip4j来实现.具体可以参看该文<Android下zip压缩文件加密解密的完美解决方案 http:// ...

  2. Python:下载zip文件并解压zip文件数据

    以下载百度地图官方给出的中国各大城市中心经纬度压缩文件( https://mapopen-website-wiki.bj.bcebos.com/static_zip/BaiduMap_cityCent ...

  3. 使用Jsch通过SFTP下载ZIP文件并解压

    ZIP模块用的并不是java.util下的,而是apache的commons-compress,用apache的库可以避免很多因为操作系统问题造成的编码异常. 大概流程是这样的:本地通过sftp访问服 ...

  4. 微信小程序下载zip压缩包后解压,并且打开文件查看的内容

    在开发pc端后台管理系统的时候,经常会遇到这样的需求:下载zip到本地,然后用户双击压缩包,并借助电脑端的压缩软件打开压缩包,就可以查看里面的word.excel.pdf文件里面的内容.(这种需求,毫 ...

  5. 压缩包下载后php文件怎么打开,用户下载的压缩包rar格式或zip文件如何解压 解压后就可以安装或运行里面的文件了...

    狸窝网盘中分享有很多解决方案中使用到的软件资源,下载到电脑后是一个软件的文件压缩包,有的用户下载后不知道如何解压或说解压不了,怎么办?由于狸窝所面向用户比较大众化,为方便不同年龄层次和新手的使用,这里 ...

  6. Java实现Zip文件的解压和压缩_ZipUtil

    这是一个关于Java的zip文件的解压和压缩工具类,里面除了解压和压缩还有删除.copy等其他功能. 在Java开发中,经常会遇到上传下载,有可能就会遇到解压,于是我就封装了工具类,方便使用. 在本文 ...

  7. ZIP文件夹解压小程序

    第1关:ZIP文件夹解压小程序之文件压缩 任务描述 相关知识 编程要求 测试说明 任务描述 本关任务:实现压缩文件或文件夹的功能. 相关知识 ZIP 是一种较为常见的压缩形式,在 Java 中要想实现 ...

  8. 使用java程序下载远程zip文件并解压文件( 带注释解释代码)

    带注释解释代码 package com.zcl.Test;import java.io.*; import java.net.HttpURLConnection; import java.net.So ...

  9. 怎样禁止macOS 在Safari下载的ZIP文件自动解压?

    macOS 用户在使用Safari 下载ZIP 档时,会发现macOS 会自动将ZIP 档解压.有没有方法禁止Safari 自动将下载的文档解压呢?当然有的,需要的朋友快看过来吧! 为什么Safari ...

最新文章

  1. 7-3 逆序的三位数 (Java)
  2. 方法总比困难多_只是为了生活
  3. 154 Find Minimum in Rotated Sorted Array 2
  4. 滴滴Uber合并?光大是不行的
  5. 微型计算机字,在微型计算机的汉字系统中,一个汉字的内码占 – 手机爱问
  6. HDU - 1584 蜘蛛牌(dfs+最优性剪枝)
  7. erp采购总监个人总结_erp采购总监总结.docx
  8. js中的forEach
  9. 二叉树——数据结构课堂作业
  10. element引入的组件大小高度不对_ElementUI 在 按需引入时定义 default size?
  11. 一段简单的python代码_一个简单的python写的C/S程序
  12. 约数之和(分治,公式变形)
  13. CCSK云安全认证-M2-云基础设施安全
  14. 手把手实现AI诗歌生成(AI写诗)
  15. 百度谷歌一起搜 - 百Google度 - Chrome插件
  16. 【案例设计】音频可视化 解析与设计
  17. 聚合支付和它的可持续发展之路
  18. mysql 删除重复数据只保留一条记录
  19. 邮件退信“Remote Server returned '420 4.2.0 Recipient deferred because there is no Mdb'”
  20. 在Debian上用FVWM做自己的桌面

热门文章

  1. 射频电路与天线(华南理工金品公开课)学习笔记--绪论
  2. aes-256-cbc php加密js解密
  3. 儿童学python好还是c++好_少儿编程学python和C++哪个好
  4. 1407:笨小猴(C C++)
  5. autojs之开门大吉
  6. 常刺激人体五个部位可强健身体
  7. tengine简单安装_tengine安装指南
  8. 重磅!博安生物新冠中和抗体对“拉姆达”等变异毒株有效;2021投资入籍排名出炉 | 美通社头条...
  9. css sprites——CSS精灵
  10. 【原】Java学习笔记018 - 面向对象