文件下载工具类
2016-12-23 15:04
323 查看
import android.os.AsyncTask; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class MyDownAsync extends AsyncTask<String,Integer,byte[]> { private File file; private FreedomCallback freedomCallback; public MyDownAsync(File file,FreedomCallback freedomCallback) { this.file = file; this.freedomCallback=freedomCallback; } @Override protected byte[] doInBackground(String... params) { if(params[0]!=null){ saveFileFromURL(params[0],file); } return null; } @Override protected void onPostExecute( byte[] result) { freedomCallback.finished(result); super.onPostExecute(result); } public static boolean saveFileFromURL(String url, File destFile) { HttpURLConnection httpConn = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(destFile)); URL urlObj = new URL(url); httpConn = (HttpURLConnection) urlObj.openConnection(); httpConn.setRequestMethod("GET"); httpConn.setDoInput(true); httpConn.setConnectTimeout(100000); httpConn.connect(); if (httpConn.getResponseCode() == 200) { bis = new BufferedInputStream(httpConn.getInputStream()); int c = 0; byte[] buffer = new byte[8 * 1024]; while ((c = bis.read(buffer)) != -1) { bos.write(buffer, 0, c); bos.flush(); } } return true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } httpConn.disconnect(); } catch (IOException e) { e.printStackTrace(); } } return false; } public interface FreedomCallback { void finished(byte[] result); } }
File file=new File(mDownloadDir+"/"+"hello.js"); new MyDownAsync(file, new MyDownAsync.FreedomCallback() { @Override public void finished(byte[] result) { } }).execute(url);
相关文章推荐
- [Wondgirl]从零开始学React Native之View(四)
- 阿里的maven镜像地址
- ViewPager打造轮播图(Banner)\引导页(Guide)
- DLX
- 程序员学习网站
- No suitable driver found for jdbc
- sublime text不能安装插件,there are no packages available for installation。
- javascript中screenXY、clientXY、pageXY和offsetXY的区别
- javaWeb学习(3)——WebServlet格式总结
- unity3d问题集 <2> 对Vector3.Lerp 插值的理解
- 1016. Phone Bills (25)
- ajax 实现加载进度条
- ajax 实现加载进度条
- 2016-12-23 微信硬件 ble_wechat_util.h移植记录二
- touchesBegan: withEvent: 不执行解决
- 2016 ~ 每一年的事都将是故事
- 【转】bash 参数展开(Parameter Expansion)
- Codeforces 154D
- java关键字含义
- 高德地图IOS SDK AMapJPEngineInvokeException reason: 'script is nil'在ios7闪退