Android--下载zip压缩文件并解压

本文提供了一种在Android环境中下载ZIP文件并直接解压缩的方法,包括使用异步任务进行进度报告,以及处理权限需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载自 http://blog.youkuaiyun.com/chaoyu168/article/details/53787157


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

源码下载:http://download.youkuaiyun.com/detail/chaoyu168/9717756

下载:

  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.net.MalformedURLException;  
  10. import java.net.URL;  
  11. import java.net.URLConnection;  
  12.   
  13. import android.app.ProgressDialog;  
  14. import android.content.Context;  
  15. import android.content.DialogInterface;  
  16. import android.content.DialogInterface.OnCancelListener;  
  17. import android.os.AsyncTask;  
  18. import android.util.Log;  
  19.   
  20. public class DownLoaderTask extends AsyncTask<Void, Integer, Long> {  
  21.     private final String TAG = "DownLoaderTask";  
  22.     private URL mUrl;  
  23.     private File mFile;  
  24.     private ProgressDialog mDialog;  
  25.     private int mProgress = 0;  
  26.     private ProgressReportingOutputStream mOutputStream;  
  27.     private Context mContext;  
  28.     public DownLoaderTask(String url,String out,Context context){  
  29.         super();  
  30.         if(context!=null){  
  31.             mDialog = new ProgressDialog(context);  
  32.             mContext = context;  
  33.         }  
  34.         else{  
  35.             mDialog = null;  
  36.         }  
  37.           
  38.         try {  
  39.             mUrl = new URL(url);  
  40.             String fileName = new File(mUrl.getFile()).getName();  
  41.             mFile = new File(out, fileName);  
  42.             Log.d(TAG, "out="+out+", name="+fileName+",mUrl.getFile()="+mUrl.getFile());  
  43.         } catch (MalformedURLException e) {  
  44.             // TODO Auto-generated catch block  
  45.             e.printStackTrace();  
  46.         }  
  47.           
  48.     }  
  49.       
  50.     @Override  
  51.     protected void onPreExecute() {  
  52.         // TODO Auto-generated method stub  
  53.         //super.onPreExecute();  
  54.         if(mDialog!=null){  
  55.             mDialog.setTitle("Downloading...");  
  56.             mDialog.setMessage(mFile.getName());  
  57.             mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  58.             mDialog.setOnCancelListener(new OnCancelListener() {  
  59.                   
  60.                 @Override  
  61.                 public void onCancel(DialogInterface dialog) {  
  62.                     // TODO Auto-generated method stub  
  63.                     cancel(true);  
  64.                 }  
  65.             });  
  66.             mDialog.show();  
  67.         }  
  68.     }  
  69.   
  70.     @Override  
  71.     protected Long doInBackground(Void... params) {  
  72.         // TODO Auto-generated method stub  
  73.         return download();  
  74.     }  
  75.   
  76.     @Override  
  77.     protected void onProgressUpdate(Integer... values) {  
  78.         // TODO Auto-generated method stub  
  79.         //super.onProgressUpdate(values);  
  80.         if(mDialog==null)  
  81.             return;  
  82.         if(values.length>1){  
  83.             int contentLength = values[1];  
  84.             if(contentLength==-1){  
  85.                 mDialog.setIndeterminate(true);  
  86.             }  
  87.             else{  
  88.                 mDialog.setMax(contentLength);  
  89.             }  
  90.         }  
  91.         else{  
  92.             mDialog.setProgress(values[0].intValue());  
  93.         }  
  94.     }  
  95.   
  96.     @Override  
  97.     protected void onPostExecute(Long result) {  
  98.         // TODO Auto-generated method stub  
  99.         //super.onPostExecute(result);  
  100.         if(mDialog!=null&&mDialog.isShowing()){  
  101.             mDialog.dismiss();  
  102.         }  
  103.         if(isCancelled())  
  104.             return;  
  105.         ((MainActivity)mContext).showUnzipDialog();  
  106.     }  
  107.   
  108.     private long download(){  
  109.         URLConnection connection = null;  
  110.         int bytesCopied = 0;  
  111.         try {  
  112.             connection = mUrl.openConnection();  
  113.             int length = connection.getContentLength();  
  114.             if(mFile.exists()&&length == mFile.length()){  
  115.                 Log.d(TAG, "file "+mFile.getName()+" already exits!!");  
  116.                 return 0l;  
  117.             }  
  118.             mOutputStream = new ProgressReportingOutputStream(mFile);  
  119.             publishProgress(0,length);  
  120.             bytesCopied =copy(connection.getInputStream(),mOutputStream);  
  121.             if(bytesCopied!=length&&length!=-1){  
  122.                 Log.e(TAG, "Download incomplete bytesCopied="+bytesCopied+", length"+length);  
  123.             }  
  124.             mOutputStream.close();  
  125.         } catch (IOException e) {  
  126.             // TODO Auto-generated catch block  
  127.             e.printStackTrace();  
  128.         }  
  129.         return bytesCopied;  
  130.     }  
  131.     private int copy(InputStream input, OutputStream output){  
  132.         byte[] buffer = new byte[1024*8];  
  133.         BufferedInputStream in = new BufferedInputStream(input, 1024*8);  
  134.         BufferedOutputStream out  = new BufferedOutputStream(output, 1024*8);  
  135.         int count =0,n=0;  
  136.         try {  
  137.             while((n=in.read(buffer, 01024*8))!=-1){  
  138.                 out.write(buffer, 0, n);  
  139.                 count+=n;  
  140.             }  
  141.             out.flush();  
  142.         } catch (IOException e) {  
  143.             // TODO Auto-generated catch block  
  144.             e.printStackTrace();  
  145.         }finally{  
  146.             try {  
  147.                 out.close();  
  148.             } catch (IOException e) {  
  149.                 // TODO Auto-generated catch block  
  150.                 e.printStackTrace();  
  151.             }  
  152.             try {  
  153.                 in.close();  
  154.             } catch (IOException e) {  
  155.                 // TODO Auto-generated catch block  
  156.                 e.printStackTrace();  
  157.             }  
  158.         }  
  159.         return count;  
  160.     }  
  161.     private final class ProgressReportingOutputStream extends FileOutputStream{  
  162.   
  163.         public ProgressReportingOutputStream(File file)  
  164.                 throws FileNotFoundException {  
  165.             super(file);  
  166.             // TODO Auto-generated constructor stub  
  167.         }  
  168.   
  169.         @Override  
  170.         public void write(byte[] buffer, int byteOffset, int byteCount)  
  171.                 throws IOException {  
  172.             // TODO Auto-generated method stub  
  173.             super.write(buffer, byteOffset, byteCount);  
  174.             mProgress += byteCount;  
  175.             publishProgress(mProgress);  
  176.         }  
  177.           
  178.     }  
  179. }  
解压:

  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.util.Enumeration;  
  10. import java.util.zip.ZipEntry;  
  11. import java.util.zip.ZipException;  
  12. import java.util.zip.ZipFile;  
  13.   
  14. import android.app.ProgressDialog;  
  15. import android.content.Context;  
  16. import android.content.DialogInterface;  
  17. import android.content.DialogInterface.OnCancelListener;  
  18. import android.os.AsyncTask;  
  19. import android.util.Log;  
  20.   
  21. public class ZipExtractorTask extends AsyncTask<Void, Integer, Long> {  
  22.     private final String TAG = "ZipExtractorTask";  
  23.     private final File mInput;  
  24.     private final File mOutput;  
  25.     private final ProgressDialog mDialog;  
  26.     private int mProgress = 0;  
  27.     private final Context mContext;  
  28.     private boolean mReplaceAll;  
  29.     public ZipExtractorTask(String in, String out, Context context, boolean replaceAll){  
  30.         super();  
  31.         mInput = new File(in);  
  32.         mOutput = new File(out);  
  33.         if(!mOutput.exists()){  
  34.             if(!mOutput.mkdirs()){  
  35.                 Log.e(TAG, "Failed to make directories:"+mOutput.getAbsolutePath());  
  36.             }  
  37.         }  
  38.         if(context!=null){  
  39.             mDialog = new ProgressDialog(context);  
  40.         }  
  41.         else{  
  42.             mDialog = null;  
  43.         }  
  44.         mContext = context;  
  45.         mReplaceAll = replaceAll;  
  46.     }  
  47.     @Override  
  48.     protected Long doInBackground(Void... params) {  
  49.         // TODO Auto-generated method stub  
  50.         return unzip();  
  51.     }  
  52.       
  53.     @Override  
  54.     protected void onPostExecute(Long result) {  
  55.         // TODO Auto-generated method stub  
  56.         //super.onPostExecute(result);  
  57.         if(mDialog!=null&&mDialog.isShowing()){  
  58.             mDialog.dismiss();  
  59.         }  
  60.         if(isCancelled())  
  61.             return;  
  62.     }  
  63.     @Override  
  64.     protected void onPreExecute() {  
  65.         // TODO Auto-generated method stub  
  66.         //super.onPreExecute();  
  67.         if(mDialog!=null){  
  68.             mDialog.setTitle("Extracting");  
  69.             mDialog.setMessage(mInput.getName());  
  70.             mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  71.             mDialog.setOnCancelListener(new OnCancelListener() {  
  72.                   
  73.                 @Override  
  74.                 public void onCancel(DialogInterface dialog) {  
  75.                     // TODO Auto-generated method stub  
  76.                     cancel(true);  
  77.                 }  
  78.             });  
  79.             mDialog.show();  
  80.         }  
  81.     }  
  82.     @Override  
  83.     protected void onProgressUpdate(Integer... values) {  
  84.         // TODO Auto-generated method stub  
  85.         //super.onProgressUpdate(values);  
  86.         if(mDialog==null)  
  87.             return;  
  88.         if(values.length>1){  
  89.             int max=values[1];  
  90.             mDialog.setMax(max);  
  91.         }  
  92.         else  
  93.             mDialog.setProgress(values[0].intValue());  
  94.     }  
  95.     private long unzip(){  
  96.         long extractedSize = 0L;  
  97.         Enumeration<ZipEntry> entries;  
  98.         ZipFile zip = null;  
  99.         try {  
  100.             zip = new ZipFile(mInput);  
  101.             long uncompressedSize = getOriginalSize(zip);  
  102.             publishProgress(0, (int) uncompressedSize);  
  103.               
  104.             entries = (Enumeration<ZipEntry>) zip.entries();  
  105.             while(entries.hasMoreElements()){  
  106.                 ZipEntry entry = entries.nextElement();  
  107.                 if(entry.isDirectory()){  
  108.                     continue;  
  109.                 }  
  110.                 File destination = new File(mOutput, entry.getName());  
  111.                 if(!destination.getParentFile().exists()){  
  112.                     Log.e(TAG, "make="+destination.getParentFile().getAbsolutePath());  
  113.                     destination.getParentFile().mkdirs();  
  114.                 }  
  115.                 if(destination.exists()&&mContext!=null&&!mReplaceAll){  
  116.                       
  117.                 }  
  118.                 ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);  
  119.                 extractedSize+=copy(zip.getInputStream(entry),outStream);  
  120.                 outStream.close();  
  121.             }  
  122.         } catch (ZipException e) {  
  123.             // TODO Auto-generated catch block  
  124.             e.printStackTrace();  
  125.         } catch (IOException e) {  
  126.             // TODO Auto-generated catch block  
  127.             e.printStackTrace();  
  128.         }finally{  
  129.             try {  
  130.                 zip.close();  
  131.             } catch (IOException e) {  
  132.                 // TODO Auto-generated catch block  
  133.                 e.printStackTrace();  
  134.             }  
  135.         }  
  136.   
  137.         return extractedSize;  
  138.     }  
  139.   
  140.     private long getOriginalSize(ZipFile file){  
  141.         Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) file.entries();  
  142.         long originalSize = 0l;  
  143.         while(entries.hasMoreElements()){  
  144.             ZipEntry entry = entries.nextElement();  
  145.             if(entry.getSize()>=0){  
  146.                 originalSize+=entry.getSize();  
  147.             }  
  148.         }  
  149.         return originalSize;  
  150.     }  
  151.       
  152.     private int copy(InputStream input, OutputStream output){  
  153.         byte[] buffer = new byte[1024*8];  
  154.         BufferedInputStream in = new BufferedInputStream(input, 1024*8);  
  155.         BufferedOutputStream out  = new BufferedOutputStream(output, 1024*8);  
  156.         int count =0,n=0;  
  157.         try {  
  158.             while((n=in.read(buffer, 01024*8))!=-1){  
  159.                 out.write(buffer, 0, n);  
  160.                 count+=n;  
  161.             }  
  162.             out.flush();  
  163.         } catch (IOException e) {  
  164.             // TODO Auto-generated catch block  
  165.             e.printStackTrace();  
  166.         }finally{  
  167.             try {  
  168.                 out.close();  
  169.             } catch (IOException e) {  
  170.                 // TODO Auto-generated catch block  
  171.                 e.printStackTrace();  
  172.             }  
  173.             try {  
  174.                 in.close();  
  175.             } catch (IOException e) {  
  176.                 // TODO Auto-generated catch block  
  177.                 e.printStackTrace();  
  178.             }  
  179.         }  
  180.         return count;  
  181.     }  
  182.       
  183.     private final class ProgressReportingOutputStream extends FileOutputStream{  
  184.   
  185.         public ProgressReportingOutputStream(File file)  
  186.                 throws FileNotFoundException {  
  187.             super(file);  
  188.             // TODO Auto-generated constructor stub  
  189.         }  
  190.   
  191.         @Override  
  192.         public void write(byte[] buffer, int byteOffset, int byteCount)  
  193.                 throws IOException {  
  194.             // TODO Auto-generated method stub  
  195.             super.write(buffer, byteOffset, byteCount);  
  196.             mProgress += byteCount;  
  197.             publishProgress(mProgress);  
  198.         }  
  199.           
  200.     }  
  201. }  

权限:

  1. <uses-permission android:name="android.permission.INTERNET" />  
  2.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  3.     <!-- 创建和删除文件 -->  
  4.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />  
  5.     <!-- 写文件 -->  
  6.     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  
  7.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  8.     <uses-permission android:name="android.permission.READ_PHONE_STATE" />  
  9.     <uses-permission android:name="android.permission.VIBRATE" />  
  10.     <uses-permission android:name="android.permission.READ_APN_SETTINGS" />  
  11.     <uses-permission android:name="android.permission.RESTART_PACKAGES"/>  
  12.   
  13.     <!-- 统计 -->  
  14.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  15.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  16.     <uses-permission android:name="android.permission.READ_PHONE_STATE" />  
  17.     <uses-permission android:name="android.permission.READ_LOGS" />  
  18.     <uses-permission android:name="android.permission.WAKE_LOCK" />  
  19.     <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" /> 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值