Android 实现文件的下载
2011-06-02 11:20
369 查看
public void downFile(String url, String path, String fileName) throws IOException { if (fileName == null || fileName == "") this.FileName = url.substring(url.lastIndexOf("/") + 1); else this.FileName = fileName; // 取得文件名,如果输入新文件名,则使用新文件名 URL Url = new URL(url); URLConnection conn = Url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); this.fileSize = conn.getContentLength();// 根据响应获取文件大小 if (this.fileSize <= 0) { // 获取内容长度为0 throw new RuntimeException("无法获知文件大小 "); } if (is == null) { // 没有下载流 sendMsg(Down_ERROR); throw new RuntimeException("无法获取文件"); } FileOutputStream FOS = new FileOutputStream(path + this.FileName); // 创建写入文件内存流,通过此流向目标写文件 byte buf[] = new byte[1024]; downLoadFilePosition = 0; int numread; while ((numread = is.read(buf)) != -1) { FOS.write(buf, 0, numread); downLoadFilePosition += numread } try { is.close(); } catch (Exception ex) { ; } }
private Handler downloadHandler = new Handler() { // 用于接收消息,处理进度条 @Override public void handleMessage(Message msg) { // 接收到的消息,并且对接收到的消息进行处理 if (!Thread.currentThread().isInterrupted()) { switch (msg.what) { case DOWN_START: pb.setMax(fileSize); //设置开始长度 case DOWN_POSITION: pb.setProgress(downLoadFilePosition); // 设置进度 break; case DOWN_COMPLETE: Toast.makeText(DownLoadFileTest.this, "下载完成!", 1).show(); // 完成提示 break; case Down_ERROR: String error = msg.getData().getString("下载出错!"); Toast.makeText(DownLoadFileTest.this, error, 1).show(); break; } } super.handleMessage(msg); } };
相关文章推荐
- Android中使用AsyncTask实现文件下载以及进度更新提示
- 我的学习之旅:android文件下载功能的实现
- Android实现Service下载文件,Notification显示下载进度
- Android Http实现文件的上传和下载
- Android快速实现文件下载(只有4行代码)
- struts2中通过Action以InputStream的下载文件以及在iOS以及Android端接收的实现方式
- Android编程实现文本文件下载
- Android实现基于http协议的文件下载
- Android okhttp+rxjava实现多文件下载和断点续传
- android 实现具有进度描述的多列表文件下载
- Android通过startService实现文件批量下载
- android自定义Dialog实现文件下载和下载进度
- Android文件下载进度条的实现
- Android 快速实现文件下载(只有4行代码)
- Android Webview实现文件下载功能
- Android实现网络多线程文件下载
- Android 实现apk文件下载并自动安装
- android实现文件下载的几种方式
- Android文件下载(实现断点续传)
- android实现文件下载功能