This article provides 2 pieces of Android code, the implementation of the download from the Android client zip file and implementation of the ZIP file decompression function, very practical, the need for Android developers can try.
Download:
Downloadertask.java
Copy Code code as follows:
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);
}
}
}
Extract:
Zipextractortask. java
Copy Code code as follows:
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, String, 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);
}
}
}
Main activity
Mainactivity.java
Copy Code code as follows:
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 ("confirmation")
. Setmessage ("Do you want to download?) ")
. Setpositivebutton ("Yes", new Onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
TODO auto-generated Method Stub
LOG.D (TAG, "OnClick 1 =" +which);
Dodownloadwork ();
}
})
. Setnegativebutton ("No", 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 ("confirmation")
. Setmessage ("Do you unpack?) ")
. Setpositivebutton ("Yes", new Onclicklistener () {
@Override
public void OnClick (Dialoginterface dialog, int which) {
TODO auto-generated Method Stub
LOG.D (TAG, "OnClick 1 =" +which);
Dozipextractorwork ();
}
})
. Setnegativebutton ("No", 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 ();
}
}
The above is the implementation of the Android zip file download and decompression function, I hope to help you.