Android中实现下载和解压zip文件功能代码分享
本文提供了2段android代码,实现了从android客户端下载zip文件并且实现zip文件的解压功能,非常实用,有需要的android开发者可以尝试一下。
下载:
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 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
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实现zip文件下载和解压功能,希望对你有所帮助。