`

Android 文件下载与解压缩

阅读更多
转载:http://blog.csdn.net/hopehe888999/article/details/19035373

    package com.johnny.testzipanddownload;  
      
    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, 0, 1024*8))!=-1){  
                    out.write(buffer, 0, 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);  
            }  
              
        }  
    }  




   
package com.johnny.testzipanddownload;  
      
    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, 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;  
        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());  
                }  
            }  
            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, 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 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);  
            }  
              
        }  
    }  



  
 package com.johnny.testzipanddownload;  
      
    import android.os.Bundle;  
    import android.os.Environment;  
    import android.app.Activity;  
    import android.app.AlertDialog;  
    import android.content.DialogInterface;  
    import android.content.DialogInterface.OnClickListener;  
    import android.util.Log;  
    import android.view.Menu;  
      
    public class MainActivity extends Activity {  
      
        private final String TAG="MainActivity";  
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
      
            Log.d(TAG, "Environment.getExternalStorageDirectory()="+Environment.getExternalStorageDirectory());  
            Log.d(TAG, "getCacheDir().getAbsolutePath()="+getCacheDir().getAbsolutePath());  
              
            showDownLoadDialog();  
            //doZipExtractorWork();  
            //doDownLoadWork();  
        }  
      
        @Override  
        public boolean onCreateOptionsMenu(Menu menu) {  
            // Inflate the menu; this adds items to the action bar if it is present.  
            getMenuInflater().inflate(R.menu.main, menu);  
            return true;  
        }  
          
        private void showDownLoadDialog(){  
            new AlertDialog.Builder(this).setTitle("确认")  
            .setMessage("是否下载?")  
            .setPositiveButton("是", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                    // TODO Auto-generated method stub  
                    Log.d(TAG, "onClick 1 = "+which);  
                    doDownLoadWork();  
                }  
            })  
            .setNegativeButton("否", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                    // TODO Auto-generated method stub  
                    Log.d(TAG, "onClick 2 = "+which);  
                }  
            })  
            .show();  
        }  
          
        public void showUnzipDialog(){  
            new AlertDialog.Builder(this).setTitle("确认")  
            .setMessage("是否解压?")  
            .setPositiveButton("是", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                    // TODO Auto-generated method stub  
                    Log.d(TAG, "onClick 1 = "+which);  
                    doZipExtractorWork();  
                }  
            })  
            .setNegativeButton("否", new OnClickListener() {  
                  
                @Override  
                public void onClick(DialogInterface dialog, int which) {  
                    // TODO Auto-generated method stub  
                    Log.d(TAG, "onClick 2 = "+which);  
                }  
            })  
            .show();  
        }  
          
        public void doZipExtractorWork(){  
            //ZipExtractorTask task = new ZipExtractorTask("/storage/usb3/system.zip", "/storage/emulated/legacy/", this, true);  
            ZipExtractorTask task = new ZipExtractorTask("/storage/emulated/legacy/testzip.zip", "/storage/emulated/legacy/", this, true);  
            task.execute();  
        }  
          
        private void doDownLoadWork(){  
            DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/testzip.zip", "/storage/emulated/legacy/", this);  
            //DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/test.h264", getCacheDir().getAbsolutePath()+"/", this);  
            task.execute();  
        }  
      
    }  
分享到:
评论

相关推荐

    java android zip解压缩(解决压缩中文乱码问题)

    本篇文章将深入探讨如何在Android平台上解决Java ZIP库在解压缩中文文件时出现的乱码问题。 首先,我们要明白乱码问题的根源。在文件的压缩和解压缩过程中,文件名通常被编码为字节序列,这个序列取决于原始文件名...

    Android 解压缩文件

    Android解压缩文件。Android原生的解压缩文件,使用时提供保存的路径即可

    安卓文件下载上传解压相关-android平台的7z压缩与解压缩.rar

    在Android平台上,处理文件下载、上传以及压缩与解压缩是常见的任务。7z是一种高效的压缩格式,具有较高的压缩率和良好的兼容性。本资源“安卓文件下载上传解压相关-android平台的7z压缩与解压缩.rar”可能包含了...

    解压缩全能王二维码生成器exe文件+手机apk

    解压缩全能王提供对apk文件的支持,意味着用户可以直接在软件中打开和管理这些移动应用文件,无论是下载的还是从其他压缩包解压出来的。 解压缩全能王电脑版与手机版apk结合,意味着用户可以在桌面和移动设备上无缝...

    android 压缩 解压缩

    `DemoZipUtils`是一个工具类,专门用于在Android平台上实现文件和文件夹的压缩与解压缩功能。下面将详细介绍这个工具类可能包含的关键知识点以及相关技术。 1. **ZIP文件格式**:ZIP是一种广泛使用的文件压缩格式,...

    javaandroid可用的ziprar解压缩代码实现.rar

    在Android平台上,对ZIP和RAR文件进行解压缩是常见的需求,比如在安装APK应用、更新资源文件或者处理用户上传的数据时。JavaAndroid可用的ziprar解压缩代码实现提供了这样的功能,但请注意,由于文件数量多,可能...

    Android 在线下载压缩包并解压到指定目录.zip

    Android提供了`java.util.zip`包,其中`ZipInputStream`和`ZipEntry`用于解压缩。首先,创建一个`ZipInputStream`,传入下载好的压缩文件的输入流。然后,遍历`ZipInputStream`,每次读取一个`ZipEntry`,创建对应...

    Android的zip解压缩

    本文将深入探讨如何在Android平台上进行zip文件的解压缩操作。 首先,我们需要理解zip文件的基本概念。Zip是一种常用的文件格式,用于存储多个文件和目录在一个单一的、可压缩的档案中。在Android上,我们可以使用...

    android的Zip压缩包下载以及解压缩

    总结,Android应用处理Zip文件下载与解压缩涉及多个步骤,包括网络请求、文件操作、解压缩算法以及异步处理。理解这些概念和技术对于开发Android应用是至关重要的。通过以上介绍,你应该能够实现从指定URL下载Zip...

    Android 加密压缩解密解压缩字符串简单DEMO

    "Android 加密压缩解密解压缩字符串简单DEMO"是一个示例项目,它展示了如何处理字符串的加密、压缩、解密和解压缩过程,这对于处理大量数据在后台与前台之间传输的情况非常有用。下面,我们将详细探讨这些关键知识点...

    Android-针对AndroidO和AndroidP的解压缩脚本

    总之,"Frida-Android-unpack-master"是一个针对Android O和P的高级解压缩解决方案,它利用了Frida的强大功能,为开发者提供了深入研究和调试APK文件的能力。这种工具在安全分析、应用调试、性能优化以及逆向工程等...

    Android例子源码支持解压缩的安卓文件管理器.zip

    另外还可以进行常规的复制移动删除重命名等操作,压缩文件的时候只能压缩成zip格式,不支持rar格式,解压缩也是紧支持zip格式,源码有比较详细的注释,需要的朋友可以下载研究一下默认编码UTF-8编译版本2.3.3,

    java、android可用的zip、rar解压缩代码实现

    本文将详细介绍如何在Android和Java环境中实现zip和rar文件的解压缩。 首先,让我们关注zip文件。在Java中,`java.util.zip`包提供了对zip文件的支持。你可以使用`ZipInputStream`来读取zip文件,并通过`ZipEntry`...

    Android将assets中的zip压缩文件解压到SD卡

    在Android开发中,有时我们需要将应用内部的资源文件,如ZIP压缩文件,解压到外部存储(即SD卡)上,以便用户可以访问或使用这些数据。本文将详细讲解如何实现这一功能,主要涉及Android权限管理、文件操作以及ZIP...

    Android例子源码支持解压缩的安卓文件管理器

    另外还可以进行常规的复制移动删除重命名等操作,压缩文件的时候只能压缩成zip格式,不支持rar格式,解压缩也是紧支持zip格式,源码有比较详细的注释,需要的朋友可以下载研究一下默认编码UTF-8编译版本2.3.3,

    Android 解、压缩文件

    在Android平台上,对文件进行解压缩是常见的操作,这在处理数据存储、更新应用程序资源或者传输数据时尤其有用。本文将深入探讨如何使用Android SDK中的API来实现文件的解压缩和压缩。 首先,我们来看解压缩文件的...

    Android安卓img镜像文件解压,安卓备份文件解压,安卓备份的img文件解压缩

    需要解压安卓备份的img文件的来拿把,在Windows中查看img,支持XP,VISTA,WIN7,WIN8,更高.. Android安卓img镜像文件解压,安卓备份文件解压,安卓备份的img文件解压缩 很方便

    (安卓APP项目源代码)文件管理器源码,文件拖曳,list弹性,root ,zip压缩解.zip

    (安卓APP项目源代码)文件管理器源码,文件拖曳,list弹性,root ,zip压缩解.zip(安卓APP项目源代码)文件管理器源码,文件拖曳,list弹性,root ,zip压缩解.zip(安卓APP项目源代码)文件管理器源码,文件拖曳,list弹性,...

    android文件下载上传&解压

    - **ZIP解压**:Android内置了`ZipFile`类,可以读取ZIP格式的压缩文件,遍历每个条目并解压缩到目标目录。`Inflater`用于解压缩数据。 - **RAR解压**:RAR格式解压需要第三方库,如`android-rar`,因为它不是...

Global site tag (gtag.js) - Google Analytics