Android实现下载zip压缩文件并解压的方法(附源码)

Android实现下载zip压缩文件并解压的方法(附源码),第1张

概述前言其实在网上有很多介绍下载文件或者解压zip文件的文章,但是两者结合的不多,所以这篇文章在此记录一下下载zip文件并直接解压的方法,直接上代码,文末有源码下载。

前言

其实在网上有很多介绍下载文件或者解压zip文件的文章,但是两者结合的不多,所以这篇文章在此记录一下下载zip文件并直接解压的方法,直接上代码,文末有源码下载。

下载:

import java.io.BufferedinputStream; import java.io.bufferedoutputstream; import java.io.file; import java.io.fileNotFoundException; import java.io.fileOutputStream; import java.io.IOException; import java.io.inputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;  import androID.app.ProgressDialog; import androID.content.Context; import androID.content.DialogInterface; import androID.content.DialogInterface.OnCancelListener; import androID.os.AsyncTask; import androID.util.Log;  public class DownLoaderTask extends AsyncTask<VoID,Integer,Long> {  private final String TAG = "DownLoaderTask";  private URL mUrl;  private file mfile;  private ProgressDialog mDialog;  private int mProgress = 0;  private ProgressReportingOutputStream mOutputStream;  private Context mContext;  public DownLoaderTask(String url,String out,Context context){   super();   if(context!=null){    mDialog = new ProgressDialog(context);    mContext = context;   }   else{    mDialog = null;   }      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) {    // Todo auto-generated catch block    e.printstacktrace();   }     }    @OverrIDe  protected voID onPreExecute() {   // Todo auto-generated method stub   //super.onPreExecute();   if(mDialog!=null){    mDialog.setTitle("Downloading...");    mDialog.setMessage(mfile.getname());    mDialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL);    mDialog.setonCancelListener(new OnCancelListener() {          @OverrIDe     public voID onCancel(DialogInterface dialog) {      // Todo auto-generated method stub      cancel(true);     }    });    mDialog.show();   }  }   @OverrIDe  protected Long doInBackground(VoID... params) {   // Todo auto-generated method stub   return download();  }   @OverrIDe  protected voID onProgressUpdate(Integer... values) {   // Todo auto-generated method stub   //super.onProgressUpdate(values);   if(mDialog==null)    return;   if(values.length>1){    int contentLength = values[1];    if(contentLength==-1){     mDialog.setIndeterminate(true);    }    else{     mDialog.setMax(contentLength);    }   }   else{    mDialog.setProgress(values[0].intValue());   }  }   @OverrIDe  protected voID onPostExecute(Long result) {   // Todo auto-generated method stub   //super.onPostExecute(result);   if(mDialog!=null&&mDialog.isShowing()){    mDialog.dismiss();   }   if(isCancelled())    return;   ((MainActivity)mContext).showUnzipDialog();  }   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 block    e.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,1024*8))!=-1){     out.write(buffer,n);     count+=n;    }    out.flush();   } catch (IOException e) {    // Todo auto-generated catch block    e.printstacktrace();   }finally{    try {     out.close();    } catch (IOException e) {     // Todo auto-generated catch block     e.printstacktrace();    }    try {     in.close();    } catch (IOException e) {     // Todo auto-generated catch block     e.printstacktrace();    }   }   return count;  }  private final class ProgressReportingOutputStream extends fileOutputStream{    public ProgressReportingOutputStream(file file)     throws fileNotFoundException {    super(file);    // Todo auto-generated constructor stub   }    @OverrIDe   public voID write(byte[] buffer,int byteOffset,int byteCount)     throws IOException {    // Todo auto-generated method stub    super.write(buffer,byteOffset,byteCount);    mProgress += byteCount;    publishProgress(mProgress);   }     } } 

解压:

import java.io.BufferedinputStream; import java.io.bufferedoutputstream; import java.io.file; import java.io.fileNotFoundException; import java.io.fileOutputStream; import java.io.IOException; import java.io.inputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.Zipfile;  import androID.app.ProgressDialog; import androID.content.Context; import androID.content.DialogInterface; import androID.content.DialogInterface.OnCancelListener; import androID.os.AsyncTask; import androID.util.Log;  public class ZipExtractorTask extends AsyncTask<VoID,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;  public ZipExtractorTask(String in,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());    }   }   if(context!=null){    mDialog = new ProgressDialog(context);   }   else{    mDialog = null;   }   mContext = context;   mReplaceAll = replaceAll;  }  @OverrIDe  protected Long doInBackground(VoID... params) {   // Todo auto-generated method stub   return unzip();  }    @OverrIDe  protected voID onPostExecute(Long result) {   // Todo auto-generated method stub   //super.onPostExecute(result);   if(mDialog!=null&&mDialog.isShowing()){    mDialog.dismiss();   }   if(isCancelled())    return;  }  @OverrIDe  protected voID onPreExecute() {   // Todo auto-generated method stub   //super.onPreExecute();   if(mDialog!=null){    mDialog.setTitle("Extracting");    mDialog.setMessage(minput.getname());    mDialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL);    mDialog.setonCancelListener(new OnCancelListener() {          @OverrIDe     public voID onCancel(DialogInterface dialog) {      // Todo auto-generated method stub      cancel(true);     }    });    mDialog.show();   }  }  @OverrIDe  protected voID onProgressUpdate(Integer... values) {   // Todo auto-generated method stub   //super.onProgressUpdate(values);   if(mDialog==null)    return;   if(values.length>1){    int max=values[1];    mDialog.setMax(max);   }   else    mDialog.setProgress(values[0].intValue());  }  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 block    e.printstacktrace();   } catch (IOException e) {    // Todo auto-generated catch block    e.printstacktrace();   }finally{    try {     zip.close();    } catch (IOException e) {     // Todo auto-generated catch block     e.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,n);     count+=n;    }    out.flush();   } catch (IOException e) {    // Todo auto-generated catch block    e.printstacktrace();   }finally{    try {     out.close();    } catch (IOException e) {     // Todo auto-generated catch block     e.printstacktrace();    }    try {     in.close();    } catch (IOException e) {     // Todo auto-generated catch block     e.printstacktrace();    }   }   return count;  }    private final class ProgressReportingOutputStream extends fileOutputStream{    public ProgressReportingOutputStream(file file)     throws fileNotFoundException {    super(file);    // Todo auto-generated constructor stub   }    @OverrIDe   public voID write(byte[] buffer,byteCount);    mProgress += byteCount;    publishProgress(mProgress);   }     } } 

权限:

<uses-permission androID:name="androID.permission.INTERNET" />  <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE" />  <!-- 创建和删除文件 -->  <uses-permission androID:name="androID.permission.MOUNT_UNMOUNT_fileSYstemS" />  <!-- 写文件 -->  <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE" />  <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE" />  <uses-permission androID:name="androID.permission.READ_PHONE_STATE" />  <uses-permission androID:name="androID.permission.VIBRATE" />  <uses-permission androID:name="androID.permission.READ_APN_SETTINGS" />  <uses-permission androID:name="androID.permission.RESTART_PACKAGES"/>   <!-- 统计 -->  <uses-permission androID:name="androID.permission.ACCESS_WIFI_STATE" />  <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE" />  <uses-permission androID:name="androID.permission.READ_PHONE_STATE" />  <uses-permission androID:name="androID.permission.READ_LOGS" />  <uses-permission androID:name="androID.permission.WAKE_LOCK" />  <uses-permission androID:name="androID.permission.CHANGE_CONfigURATION" /> 

源码下载:点击这里

总结

以上就是这篇文章的全部内容了,希望这篇文章对各位AndroID开发者们能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程小技巧能带来一定的帮助。

总结

以上是内存溢出为你收集整理的Android实现下载zip压缩文件并解压的方法(附源码)全部内容,希望文章能够帮你解决Android实现下载zip压缩文件并解压的方法(附源码)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1146870.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存