【android】下载文件至本应用程序的file目录或者sdcard
2024-10-19 13:23:48
一、判断是否有sdcard卡
//判断是否有SD卡 //ture:有SD卡 //false:没有SD卡 public boolean avaiableMedia(){ String status=Environment.getExternalStorageState(); if(status.equals(Environment.MEDIA_MOUNTED)){ return true; } else { return false; } }
二、下载文件至sdcard卡
if(avaiableMedia()){ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; if (is != null) { File file = new File(Environment.getExternalStorageDirectory(),"test.apk"); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; int count = 0; while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); count += ch; } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } if (is != null) { is.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
三、下载文件至本应用程序的数据文件夹
else{ try { FileOutputStream outStream = this.openFileOutput("test.apk" , Context.MODE_WORLD_READABLE); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); int count = 0; if (is != null) { byte[] buf = new byte[1024]; int ch = -1; while ((ch = is.read(buf)) >0) { outStream.write(buf,0,ch); count += ch; Toast.makeText(getApplicationContext(),"正在下载升级包...",Toast.LENGTH_SHORT).show(); } } outStream.flush(); if (outStream != null) { outStream.close(); } if (is != null) { is.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
最新文章
- UISearchBar控件-让我们来搞定!(转)
- hibernate(五) hibernate一对一关系映射详解
- Java引用机制——reference
- 【制作镜像Win*】系统配置
- Redis指令文档
- GC(Garbagecollection)垃圾回收
- ZOJ 1610 间隔染色段树
- sorted函数返回一个新的列表就安全了吗?
- iFace Chain [ 爱妃链 ] 或将凭借人脸密钥技术成为安全领域最大的赢家
- 【Eclipse】_Eclipse自动补全增强方法 &; 常用快捷键
- SpringBoot无废话入门01:最简SpringBoot应用
- 微信小程序开发笔记02
- 移动端web页面开发常用的头部标签设置
- 【SqlServer】解析SqlServer的分页
- 梦殇 chapter five
- spring boot mybatis sql打印到控制台
- seq 序列
- [Oracle]OpenVMS 运行 Oracle 时的推荐值
- git pull 总要求输入账号和密码解决?
- ETL利器Kettle实战应用解析系列三
热门文章
- wtforms Form实例化流程(源码解析)
- 第七课 GDB调试 (下)
- Entity FrameWork Code First常用知识
- SweetWeather wpf天气预报源代码
- Spark机器学习8· 文本处理(spark-shell)
- app自动化测试-appium
- 2018年Java面试题搜集
- Book Review of “The practice of programming” (Ⅱ)
- Mac 使用技巧分享
- Newtonsoft.Json 序列 反序列 IEnumerable