iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >Android zip文件下载和解压实例
  • 393
分享到

Android zip文件下载和解压实例

zip解压Android 2022-06-06 10:06:50 393人浏览 薄情痞子
摘要

下载:DownLoaderTask.java 代码如下:package com.johnny.testzipanddownload; import java.io.Buffe

下载:
DownLoaderTask.java

代码如下:
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);
  }
 }
}

解压:
ZipExtractorTask .java
代码如下:
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 Progre ssReportingOutputStream(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);
  }
 }
}

Main Activity
MainActivity.java
代码如下:
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();
 }

}

您可能感兴趣的文章:Android WEBView实现文件下载功能Android使用WebView实现文件下载功能Android编程使用WebView实现文件下载功能的两种方法解决Android SDK下载和更新失败的方法详解Android文件下载进度条的实现代码Android Studio使用教程(一):下载与安装及创建HelloWorld项目Android实现下载文件功能的方法详解Android使用OKHttp3实现下载(断点续传、显示进度)android实现通知栏下载更新app示例Android在WebView中调用系统下载的方法


--结束END--

本文标题: Android zip文件下载和解压实例

本文链接: https://www.lsjlt.com/news/27248.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java实现文件压缩为zip和解压zip压缩包
    目录压缩成.zip解压.zip压缩成.zip 代码如下: public static void toZip(String srcDir, OutputStream out) th...
    99+
    2024-04-02
  • Java如何实现文件压缩为zip和解压zip压缩包
    本篇内容介绍了“Java如何实现文件压缩为zip和解压zip压缩包”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!压缩成.zip代码如下:pu...
    99+
    2023-07-02
  • Linux下如何解压zip文件
    本篇内容主要讲解“Linux下如何解压zip文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Linux下如何解压zip文件”吧!通常情况下,Linux系统并不会产生zip文件,而是由用户把zi...
    99+
    2023-06-27
  • C#压缩或解压rar、zip文件方法实例
    前言 为了便于文件在网络中的传输和保存,通常将文件进行压缩操作,常用的压缩格式有rar、zip和7z,本文将介绍在C#中如何对这几种类型的文件进行压缩和解压,并提供一些在C#中解压缩...
    99+
    2024-04-02
  • Node.js中zip压缩和zip解压缩实例用法
    本篇内容主要讲解“Node.js中zip压缩和zip解压缩实例用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Node.js中zip压缩和zip解压缩实例用法...
    99+
    2024-04-02
  • 怎么在Linux下解压Zip文件
    这篇文章主要介绍怎么在Linux下解压Zip文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Zip 是一种创建压缩存档文件的最普通、最流行的方法。它也是一种古老的文件归档文件格式,这种格式创建于 1989 年。由于...
    99+
    2023-06-16
  • Python实现rar、zip和7z文件的压缩和解压
    一、7z压缩文件的压缩和解压 1、安装py7zr 我们要先安装py7zr第三方库: pip install py7zr 如果python环境有问题,执行上面那一条安装语句老是安装在默认的python环...
    99+
    2023-09-20
    python
  • go怎么压缩和解压zip文件
    本篇内容主要讲解“go怎么压缩和解压zip文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“go怎么压缩和解压zip文件”吧!压缩zipfunc Zip(dest strin...
    99+
    2023-07-02
  • go压缩解压zip文件源码示例
    目录压缩zip解压zip压缩zip func Zip(dest string, paths ...string) error { zfile, err := os.Creat...
    99+
    2024-04-02
  • Android开发中怎么实现一个下载zip压缩文件的功能
    今天就跟大家聊聊有关Android开发中怎么实现一个下载zip压缩文件的功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。下载:import java.io.BufferedInpu...
    99+
    2023-05-31
    android roi
  • vue实现zip文件下载
    本文实例为大家分享了vue实现zip文件下载的具体代码,供大家参考,具体内容如下 el-button按钮 <el-button size="mini" type="succ...
    99+
    2024-04-02
  • Linux系统下如何解压zip文件
    这篇文章主要介绍Linux系统下如何解压zip文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Linux系统里的zip是一种创建压缩存档文件的常用方式,同时也是最流行的文件归档文件格式。为了解压 zip 归档文件,...
    99+
    2023-06-28
  • vue如何从后台下载.zip压缩包文件
    目录1.添加下载按钮2.(原始方法,会出现乱码)给按钮添加点击事件3.(更正版)用axios({})这种方式4.报跨域问题vue前后端分离,使用element的el-button组件...
    99+
    2024-04-02
  • js实现根据文件url批量压缩下载成zip包
    目录前言1. 所需包2. 安装3. 引入4. 完整代码解析使用5. 部分代码解析解析 Bolb 与 arraybuffer前言 项目开发中,产品经理提了这样一个需求:将系统中的附件实...
    99+
    2023-02-09
    js url批量压缩zip包 js url批量压缩
  • Java压缩与解压缩ZIP文件
    文章目录 前言Java解压缩文件压缩和解压缩ZIP文件检验应用总结 前言 在现代计算机上,数据传输和存储越来越依赖于文件压缩技术。当我们需要发送大量数据时,压缩文件可以大大减少传输时间...
    99+
    2023-09-11
    java zip 压缩文件 解压缩文件 ZipOutputStream
  • 如何在C#中压缩和解压rar、zip文件
    这期内容当中小编将会给大家带来有关如何在C#中压缩和解压rar、zip文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。在C#.NET中压缩解压rar文件rar格式是一种具有专利文件的压缩格式,是一种商业...
    99+
    2023-06-15
  • Java对zip,rar,7z文件带密码解压实例详解
    目录前言实现代码1、pom.xml2、zip解压3、rar解压4、7z解压5、解压统一入口封装6、测试代码补充前言 在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传...
    99+
    2024-04-02
  • ubuntu如何解压zip文件
    这篇文章主要讲解了“ubuntu如何解压zip文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“ubuntu如何解压zip文件”吧! ubuntu解压zi...
    99+
    2022-12-30
    ubuntu zip文件
  • 3.7Python之解压缩ZIP文件
      zip文件格式是通用的文档压缩标准。自1.6版本起,Python中zipfile模块能够直接处理zip文件里的数据,例如需要将对应目录或多个文件打包或压缩成zip格式,或者需要查看一个zip格式的归档文件中部分或者所有文件同...
    99+
    2023-01-31
    解压缩 文件 Python
  • Java如何解压zip文件
    小编给大家分享一下Java如何解压zip文件,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!代码如下:package com.lanyuan.assemb...
    99+
    2023-05-30
    java zip
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作