一个文件下载的工具类
生活随笔
收集整理的這篇文章主要介紹了
一个文件下载的工具类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
主類:
/** * <p> * Copyright: Copyright (c) 2015 * Company: * Description: 這里寫這個文件是干什么用的 * </p> * @Title ImgDownloadUtil.java * @Package c * @version 1.0 * @author * @date 2015年9月9日 */ package com.iptvclient.android.baseclient.startupad; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Locale; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.androidsdk.download.DataDownload; import com.androidsdk.download.bean.DataAttribute; import com.androidsdk.http.bean.HttpRequest; import com.androidsdk.http.bean.HttpRequestParams; import com.androidsdk.http.bean.HttpResponse; import com.androidsdk.http.download.IHttpDownloadListener; import com.iptvclient.android.androidsdk.common.LogEx; /** * 下載保存圖片的工具類 * @ClassName:ImgDownloadUtil * @Description: 這里用一句話描述這個類的作用 * @author: * @date: 2015年9月9日 * */ public class ImgFileUtil {private static String LOG_TAG = "StartUpAdUtil"; private Context mContext; private ImgDownloadListener listener; private String mDownloadUrl; private String filename = "startupad"; private boolean saveSuccFlag = false; private String path; public ImgFileUtil(Context context, ImgDownloadListener l){this.mContext = context; this.listener = l; }public void stratDownloadImg(String url){mDownloadUrl = url; getFilename(mDownloadUrl); path = mContext.getFilesDir()+"/"+filename; doDownload(url); }private void getFilename(String url){String urlTemp = url.toLowerCase(Locale.US); LogEx.i(LOG_TAG, "img url is "+urlTemp); if (urlTemp.contains(".gif")){filename = filename+".gif"; }else if (urlTemp.contains(".jpg")){filename = filename+".jpg"; }else if (urlTemp.contains(".png")){filename = filename+".png"; }else if (urlTemp.contains(".bmp")){filename = filename+".bmp"; }LogEx.i(LOG_TAG, "filename = "+filename); }private void doDownload(String url){String downloadUrl = ""; try {downloadUrl = URLDecoder.decode(url,"UTF-8"); }catch (UnsupportedEncodingException e){e.printStackTrace(); reportSaveFileRet(); return; }HttpRequest req = new HttpRequest(HttpRequest.METHOD_GET, downloadUrl); // 網(wǎng)絡請求 DataAttribute attr = new DataAttribute(); attr.setMergeMode(DataDownload.FLAG_MERGE_MODE_LAST); attr.setUniqueKey(downloadUrl); HttpRequestParams params = new HttpRequestParams(attr, req, new IHttpDownloadListener(){@Override public void onError(Exception arg0){reportSaveFileRet(); }@Override public void onData(HttpRequest datareq, HttpResponse datarsp){do {if (null == datarsp){break; }LogEx.d(LOG_TAG, " datarsp=" + datarsp); LogEx.d(LOG_TAG, "file size = " + datarsp.getContentLength()/ 1024 + "B"); try {InputStream in = datarsp.getInputStream(); int ret = saveFile(in); if (ret ==0){saveSuccFlag = true; }in.close(); }catch (Exception e){e.printStackTrace(); LogEx.w(LOG_TAG, "" + e); break; }}while (false); reportSaveFileRet(); }@Override public void onCancel(HttpRequest arg0, HttpResponse arg1){reportSaveFileRet(); }}); DataDownload.getInstance().sendHttpRequest(params); }private int saveFile(InputStream in){if (in == null){LogEx.w(LOG_TAG, "input null."); return -1; }FileOutputStream output = null; try {output = new FileOutputStream(path); byte[] buffer = new byte[1024]; int len = 0; while (-1 != (len = in.read(buffer))){output.write(buffer, 0, len); }output.flush(); }catch (Exception e){e.printStackTrace(); LogEx.w(LOG_TAG, "save file Exception " + e); return -1; }finally {try {output.close(); }catch (Exception e){e.printStackTrace(); LogEx.w(LOG_TAG, "save file Exception " + e); return -1; }}return 0; }private void reportSaveFileRet(){if (null == listener){LogEx.w(LOG_TAG, "IStartAdFileListener is null"); return; }LogEx.i(LOG_TAG, "IStartAdFileListener is notified"); if (saveSuccFlag){listener.onImgDownloaded(filename); }else{listener.onImgDownloadFail(); }}public static InputStream readDataFile(Context context, String fileName) {FileInputStream fis = null; try {fis = context.openFileInput(fileName); } catch (FileNotFoundException e) {LogEx.w(LOG_TAG, "Read Data_No Such File"); e.printStackTrace(); }return fis; }public static Bitmap File2Bitmap(Context context,String filename) {String path = context.getFilesDir()+"/"+filename; return BitmapFactory.decodeFile(path); }public interface ImgDownloadListener{public void onImgDownloaded(String filename); public void onImgDownloadFail(); } }HttpRequest類:
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.androidsdk.http.bean; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; public class HttpRequest {public static final String METHOD_GET = "Get"; public static final String METHOD_POST = "Post"; public static final String METHOD_PUT = "Put"; String method; Map<String, String> headerMap; String url; List<NameValuePair> params; String body; Object extra; boolean canceled; boolean bAutoRedirect = true; public HttpRequest(String method) {this.method = method; this.headerMap = new HashMap(); }public HttpRequest(String method, String url) {this.method = method; this.url = url; this.headerMap = new HashMap(); }public HttpRequest(String method, String url, List<NameValuePair> params) {this.method = method; this.url = url; this.params = params; this.headerMap = new HashMap(); }public HttpRequest(String method, String url, String body) {this.method = method; this.url = url; this.body = body; this.headerMap = new HashMap(); }public HttpRequest(String method, String url, List<NameValuePair> params, String body) {this.method = method; this.url = url; this.params = params; this.body = body; this.headerMap = new HashMap(); }public boolean compareTo(Object o) {if(null == o) {return false; } else if(!(o instanceof HttpRequest)) {return false; } else {HttpRequest request = (HttpRequest)o; if(null == this.method && null != request.getMethod()) {return false; } else if(null != this.method && !this.method.equalsIgnoreCase(request.getMethod())) {return false; } else if(null == this.url && null != request.getUrl()) {return false; } else if(null != this.url && !this.url.equalsIgnoreCase(request.getUrl())) {return false; } else if((null != this.params || null == request.getParams()) && (null == this.params || null != request.getParams())) {if(null == this.params && null == request.getParams()) {return true; } else {ArrayList params1 = new ArrayList(); ArrayList params2 = new ArrayList(); Iterator i$; NameValuePair nvp; if(null != this.params && !this.params.isEmpty()) {i$ = this.params.iterator(); while(i$.hasNext()) {nvp = (NameValuePair)i$.next(); if(null != nvp && null != nvp.getName() && null != nvp.getValue()) {params1.add(nvp); }}}if(null != request.getParams() && !request.getParams().isEmpty()) {i$ = request.getParams().iterator(); while(i$.hasNext()) {nvp = (NameValuePair)i$.next(); if(null != nvp && null != nvp.getName() && null != nvp.getValue()) {params2.add(nvp); }}}if(params1.size() != params2.size()) {return false; } else {i$ = params1.iterator(); boolean bFound; do {if(!i$.hasNext()) {if(null == this.body && null != request.getBody()) {return false; }if(null != this.body && !this.body.equals(request.getBody())) {return false; }if(this.bAutoRedirect != request.isAutoRedirect()) {return false; }return true; }nvp = (NameValuePair)i$.next(); bFound = false; Iterator i$1 = params2.iterator(); while(i$1.hasNext()) {NameValuePair nvp2 = (NameValuePair)i$1.next(); if(nvp.getName().equals(nvp2.getName())) {if(!nvp.getValue().equals(nvp2.getValue())) {return false; }bFound = true; break; }}} while(bFound); return false; }}} else {return false; }}}public Map<String, String> getHeaderMap() {return this.headerMap; }public void setHeaderMap(Map<String, String> headerMap) {this.headerMap = headerMap; }public void enableAutoRedirect(boolean bEnable) {this.bAutoRedirect = bEnable; }public boolean isAutoRedirect() {return this.bAutoRedirect; }public void addHeader(String name, String value) {if(null != name && !"".equals(name.trim())) {if(null != value && !"".equals(value.trim())) {String newName = name.trim(); String newValue = value.trim(); if(this.headerMap.containsKey(newName)) {String val = (String)this.headerMap.get(newName); if(null != val && !"".equals(val)) {String[] valArray = val.split(";"); String[] sb = valArray; int len$ = valArray.length; for(int i$ = 0; i$ < len$; ++i$) {String v = sb[i$]; if(v.equalsIgnoreCase(newValue)) {return; }}StringBuilder var11 = new StringBuilder(val); var11.append(";").append(newValue); newValue = var11.toString(); }}this.headerMap.put(newName, newValue); }}}public void setHeader(String name, String value) {if(null != name && !"".equals(name.trim())) {if(null != value && !"".equals(value.trim())) {this.headerMap.put(name.trim(), value.trim()); }}}public String getMethod() {return this.method; }public void setMethod(String method) {this.method = method; }public String getUrl() {return this.url; }public void setUrl(String url) {this.url = url; }public List<NameValuePair> getParams() {return this.params; }public void setParams(List<NameValuePair> params) {this.params = params; }public String getBody() {return this.body; }public void setBody(String body) {this.body = body; }public Object getExtra() {return this.extra; }public void setExtra(Object extra) {this.extra = extra; }public boolean isCanceled() {return this.canceled; }public void setCanceled(boolean canceled) {this.canceled = canceled; } }DataAttribute接口:
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.androidsdk.download.bean; public class DataAttribute {int mergeMode; int concurrentNum; String uniqueKey; public DataAttribute() {}public int getMergeMode() {return this.mergeMode; }public void setMergeMode(int mergeMode) {this.mergeMode = mergeMode; }public int getConcurrentNum() {return this.concurrentNum; }public void setConcurrentNum(int concurrentNum) {this.concurrentNum = concurrentNum; }public String getUniqueKey() {return this.uniqueKey; }public void setUniqueKey(String uniqueKey) {this.uniqueKey = uniqueKey; } } HttpRequestParams接口: // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.androidsdk.http.bean; import com.androidsdk.download.bean.DataAttribute; import com.androidsdk.http.bean.HttpAttribute; import com.androidsdk.http.bean.HttpRequest; import com.androidsdk.http.download.IHttpDownloadListener; public class HttpRequestParams {DataAttribute attr; HttpAttribute httpAttr; HttpRequest req; IHttpDownloadListener listener; public HttpRequestParams(DataAttribute attr, HttpRequest req, IHttpDownloadListener listener) {this.attr = attr; this.req = req; this.listener = listener; }public HttpRequestParams(DataAttribute attr, HttpAttribute httpAttr, HttpRequest req, IHttpDownloadListener listener) {this.attr = attr; this.httpAttr = httpAttr; this.req = req; this.listener = listener; }public DataAttribute getAttr() {return this.attr; }public HttpAttribute getHttpAttr() {return this.httpAttr; }public void setHttpAttr(HttpAttribute httpAttr) {this.httpAttr = httpAttr; }public HttpRequest getReq() {return this.req; }public IHttpDownloadListener getListener() {return this.listener; }public void setListener(IHttpDownloadListener listener) {this.listener = listener; } }IHttpDownloadListener回調(diào)接口:
package com.androidsdk.http.download; import com.androidsdk.http.bean.HttpRequest; import com.androidsdk.http.bean.HttpResponse; public interface IHttpDownloadListener {void onError(Exception var1); void onData(HttpRequest var1, HttpResponse var2); void onCancel(HttpRequest var1, HttpResponse var2); }
總結(jié)
以上是生活随笔為你收集整理的一个文件下载的工具类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装 android studio创建工
- 下一篇: android平台使用java动态生成公