android 下载zip文件并解压
16lz
2021-01-24
公司项目有个需求, 需要下载一个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 game学习笔记(1)
- Android仿iPhone圆角边框
- Android(安卓)Studio使用OpenCV的配置方法
- Android对话框_详解
- Android(安卓)“adb”不是内部或外部命令,也不是可运行的程序或批
- 基于android studio开发的 opencv关于android人脸识别的DEMO
- android 7.0以上获取图片工具类
- [android UI]应用程序自适应屏幕大小
- android自定义ViewGroup基础