Android 文件下载与解压缩

DownLoaderTask.java

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

解压:

ZipExtractorTask .java

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


Main Activity

MainActivity.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.johnny.testzipanddownload;  
  2.   
  3. import android.os.Bundle;  
  4. import android.os.Environment;  
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.content.DialogInterface;  
  8. import android.content.DialogInterface.OnClickListener;  
  9. import android.util.Log;  
  10. import android.view.Menu;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     private final String TAG="MainActivity";  
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.   
  20.         Log.d(TAG, "Environment.getExternalStorageDirectory()="+Environment.getExternalStorageDirectory());  
  21.         Log.d(TAG, "getCacheDir().getAbsolutePath()="+getCacheDir().getAbsolutePath());  
  22.           
  23.         showDownLoadDialog();  
  24.         //doZipExtractorWork();  
  25.         //doDownLoadWork();  
  26.     }  
  27.   
  28.     @Override  
  29.     public boolean onCreateOptionsMenu(Menu menu) {  
  30.         // Inflate the menu; this adds items to the action bar if it is present.  
  31.         getMenuInflater().inflate(R.menu.main, menu);  
  32.         return true;  
  33.     }  
  34.       
  35.     private void showDownLoadDialog(){  
  36.         new AlertDialog.Builder(this).setTitle("确认")  
  37.         .setMessage("是否下载?")  
  38.         .setPositiveButton("是"new OnClickListener() {  
  39.               
  40.             @Override  
  41.             public void onClick(DialogInterface dialog, int which) {  
  42.                 // TODO Auto-generated method stub  
  43.                 Log.d(TAG, "onClick 1 = "+which);  
  44.                 doDownLoadWork();  
  45.             }  
  46.         })  
  47.         .setNegativeButton("否"new OnClickListener() {  
  48.               
  49.             @Override  
  50.             public void onClick(DialogInterface dialog, int which) {  
  51.                 // TODO Auto-generated method stub  
  52.                 Log.d(TAG, "onClick 2 = "+which);  
  53.             }  
  54.         })  
  55.         .show();  
  56.     }  
  57.       
  58.     public void showUnzipDialog(){  
  59.         new AlertDialog.Builder(this).setTitle("确认")  
  60.         .setMessage("是否解压?")  
  61.         .setPositiveButton("是"new OnClickListener() {  
  62.               
  63.             @Override  
  64.             public void onClick(DialogInterface dialog, int which) {  
  65.                 // TODO Auto-generated method stub  
  66.                 Log.d(TAG, "onClick 1 = "+which);  
  67.                 doZipExtractorWork();  
  68.             }  
  69.         })  
  70.         .setNegativeButton("否"new OnClickListener() {  
  71.               
  72.             @Override  
  73.             public void onClick(DialogInterface dialog, int which) {  
  74.                 // TODO Auto-generated method stub  
  75.                 Log.d(TAG, "onClick 2 = "+which);  
  76.             }  
  77.         })  
  78.         .show();  
  79.     }  
  80.       
  81.     public void doZipExtractorWork(){  
  82.         //ZipExtractorTask task = new ZipExtractorTask("/storage/usb3/system.zip", "/storage/emulated/legacy/", this, true);  
  83.         ZipExtractorTask task = new ZipExtractorTask("/storage/emulated/legacy/testzip.zip""/storage/emulated/legacy/"thistrue);  
  84.         task.execute();  
  85.     }  
  86.       
  87.     private void doDownLoadWork(){  
  88.         DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/testzip.zip""/storage/emulated/legacy/"this);  
  89.         //DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/test.h264", getCacheDir().getAbsolutePath()+"/", this);  
  90.         task.execute();  
  91.     }  
  92.   
  93. }  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Android解压缩文件时出现"not a directory"(不是目录)错误时,这通常表示解压缩的对象不是一个有效的目录。 出现这个错误的可能原因之一是指定的路径或文件名错误。确保你提供的路径和文件名是正确的,并且指向一个真正存在的目录。 另一个原因是解压缩的对象可能不是一个目录,而是一个文件。在Android中,解压缩函数通常期望目标路径是一个目录,而不是一个文件。如果你要解压缩的是一个文件,而不是目录,你需要修改解压缩的逻辑以适应这种情况。 解决这个问题的一种方法是在解压缩之前检查目标路径是否是一个目录。可以使用File类的isDirectory()方法来判断目标路径是否是一个目录。如果不是一个目录,你可以手动创建一个目录,然后使用解压缩函数将文件解压到这个新创建的目录中。 以下是一个示例代码片段,使用Apache Commons Compress库来解压缩文件: ``` File sourceFile = new File("path/to/source/file.zip"); File destDir = new File("path/to/destination/dir"); if (!destDir.isDirectory()) { destDir.mkdirs(); // 如果目标路径不是一个目录,创建一个新目录 } try (InputStream inputStream = new FileInputStream(sourceFile); ArchiveInputStream ais = new ArchiveStreamFactory() .createArchiveInputStream("zip", inputStream)) { ArchiveEntry entry; while ((entry = ais.getNextEntry()) != null) { File entryFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { entryFile.mkdirs(); // 如果是目录,创建一个新目录 } else { try (OutputStream outputStream = new FileOutputStream(entryFile)) { IOUtils.copy(ais, outputStream); // 拷贝文件内容 } } } } catch (IOException e) { e.printStackTrace(); } ``` 希望这些信息对你有帮助,如果问题仍然存在,请提供更多的细节和相关代码以便更好地帮助你解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值