当前位置:   article > 正文

Android实现zip文件下载和解压功能_android 下载 zipped json file

android 下载 zipped json file

关注微信号:javalearns   随时随地学Java

或扫一扫

随时随地学Java


本文提供了2段Android代码,实现了从Android客户端下载ZIP文件并且实现ZIP文件的解压功能,非常实用,有需要的Android开发者可以尝试一下。

下载:

DownLoaderTask.java

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

解压:

ZipExtractorTask .java

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

Main Activity

MainActivity.java

  1. package com.johnny.testzipanddownload;
  2. import android.os.Bundle;
  3. import android.os.Environment;
  4. import android.app.Activity;
  5. import android.app.AlertDialog;
  6. import android.content.DialogInterface;
  7. import android.content.DialogInterface.OnClickListener;
  8. import android.util.Log;
  9. import android.view.Menu;
  10. public class MainActivity extends Activity {
  11. private final String TAG="MainActivity";
  12. @Override
  13. protected void onCreate(Bundle savedInstanceState) {
  14. super.onCreate(savedInstanceState);
  15. setContentView(R.layout.activity_main);
  16. Log.d(TAG, "Environment.getExternalStorageDirectory()="+Environment.getExternalStorageDirectory());
  17. Log.d(TAG, "getCacheDir().getAbsolutePath()="+getCacheDir().getAbsolutePath());
  18. showDownLoadDialog();
  19. //doZipExtractorWork();
  20. //doDownLoadWork();
  21. }
  22. @Override
  23. public boolean onCreateOptionsMenu(Menu menu) {
  24. // Inflate the menu; this adds items to the action bar if it is present.
  25. getMenuInflater().inflate(R.menu.main, menu);
  26. return true;
  27. }
  28. private void showDownLoadDialog(){
  29. new AlertDialog.Builder(this).setTitle("确认")
  30. .setMessage("是否下载?")
  31. .setPositiveButton("是", new OnClickListener() {
  32. @Override
  33. public void onClick(DialogInterface dialog, int which) {
  34. // TODO Auto-generated method stub
  35. Log.d(TAG, "onClick 1 = "+which);
  36. doDownLoadWork();
  37. }
  38. })
  39. .setNegativeButton("否", new OnClickListener() {
  40. @Override
  41. public void onClick(DialogInterface dialog, int which) {
  42. // TODO Auto-generated method stub
  43. Log.d(TAG, "onClick 2 = "+which);
  44. }
  45. })
  46. .show();
  47. }
  48. public void showUnzipDialog(){
  49. new AlertDialog.Builder(this).setTitle("确认")
  50. .setMessage("是否解压?")
  51. .setPositiveButton("是", new OnClickListener() {
  52. @Override
  53. public void onClick(DialogInterface dialog, int which) {
  54. // TODO Auto-generated method stub
  55. Log.d(TAG, "onClick 1 = "+which);
  56. doZipExtractorWork();
  57. }
  58. })
  59. .setNegativeButton("否", new OnClickListener() {
  60. @Override
  61. public void onClick(DialogInterface dialog, int which) {
  62. // TODO Auto-generated method stub
  63. Log.d(TAG, "onClick 2 = "+which);
  64. }
  65. })
  66. .show();
  67. }
  68. public void doZipExtractorWork(){
  69. //ZipExtractorTask task = new ZipExtractorTask("/storage/usb3/system.zip", "/storage/emulated/legacy/", this, true);
  70. ZipExtractorTask task = new ZipExtractorTask("/storage/emulated/legacy/testzip.zip", "/storage/emulated/legacy/", this, true);
  71. task.execute();
  72. }
  73. private void doDownLoadWork(){
  74. DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/testzip.zip", "/storage/emulated/legacy/", this);
  75. //DownLoaderTask task = new DownLoaderTask("http://192.168.9.155/johnny/test.h264", getCacheDir().getAbsolutePath()+"/", this);
  76. task.execute();
  77. }
  78. }

以上就是Android实现zip文件下载和解压功能,希望对你有所帮助。

.................... 【.........阅读全文】

Java免费学习   Java自学网 http://www.javalearns.com

关注微信号:javalearns   随时随地学Java

或扫一扫

随时随地学Java


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/283780
推荐阅读
相关标签
  

闽ICP备14008679号