公司项目有个需求, 需要下载一个HTML文件压缩包到本地 用WebView显示html页面。网上找到了下面链接 修改了一下就可以自己用:
http://blog.csdn.net/hopehe888999/article/details/19035373
我将原方法中的很多东西进行了简化,看起来更简单明了一点。下面直接上代码:
文件下载类
public class DownLoaderTask extends AsyncTask<Void, Integer, Long> {
private final String TAG = "DownLoaderTask";
private URL mUrl;
private File mFile;
private int mProgress = 0;
private ProgressReportingOutputStream mOutputStream;
private Context mContext;
private String mTypeStr;
// 文件下载的url 保存路径 out
public DownLoaderTask(String url,String out,Context context,String typeStr){
super();
if(context!=null){
mContext = context;
mTypeStr=typeStr;
}
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) {
e.printStackTrace();
}
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Long doInBackground(Void... params) {
// TODO Auto-generated method stub
return download();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
}
//下载保存后执行
@Override
protected void onPostExecute(Long result) {
// TODO Auto-generated method stub
if(isCancelled())
return;
//解压
ZipExtractorTask task = new ZipExtractorTask(Constants.SAVE_FILES_PATH+mTypeStr,Constants.SAVE_FILES_PATH, mContext,true);
task.execute();
}
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);
}
}
}
文件解压类 对压缩文件进行解压(上面的类中 已执行解压方法)
/**
* 解压
*/
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;
WebView mWebView;
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());
}
}
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(isCancelled())
return;
//这里表示解压完成 可以进行显示WebView 发送广播 并更新保存的 时间
Intent intent = new Intent();
intent.setAction("com.sl.unzip");
mContext.sendBroadcast(intent);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
}
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);
}
}
}
我写的这个是下载完成后自动解压到对应的路径。到时候可以根据情况进行修改。最后在子线程中调用执行:
DownLoaderTask downLoaderTask= new DownLoaderTask(Constants.WEB_HTTP_URLZIP+string, Constants.SAVE_FILES_PATH, getActivity(), "/"+zipName );
downLoaderTask.execute();
下图为解压成功后的调用
vebView.loadUrl("file:///data/data/com.sl.washshop/wash_doc.html");//加载本地网页 "///"是系统默认的标识