|
| 1 | +package org.wsc.coderising.download; |
| 2 | + |
| 3 | +import org.wsc.coderising.download.api.Connection; |
| 4 | +import org.wsc.coderising.download.api.ConnectionException; |
| 5 | +import org.wsc.coderising.download.api.ConnectionManager; |
| 6 | +import org.wsc.coderising.download.api.DownloadListener; |
| 7 | + |
| 8 | +/** |
| 9 | + * 文件下载器 |
| 10 | + * |
| 11 | + * @author Administrator |
| 12 | + * @date 2017年3月6日下午7:04:44 |
| 13 | + * @version v1.0 |
| 14 | + * |
| 15 | + */ |
| 16 | +public class FileDownloader { |
| 17 | + |
| 18 | + String url; |
| 19 | + |
| 20 | + DownloadListener listener; |
| 21 | + |
| 22 | + ConnectionManager cm; |
| 23 | + |
| 24 | + |
| 25 | + public FileDownloader(String _url) { |
| 26 | + this.url = _url; |
| 27 | + |
| 28 | + } |
| 29 | + |
| 30 | + public void execute(){ |
| 31 | + // 在这里实现你的代码, 注意: 需要用多线程实现下载 |
| 32 | + // 这个类依赖于其他几个接口, 你需要写这几个接口的实现代码 |
| 33 | + // (1) ConnectionManager , 可以打开一个连接,通过Connection可以读取其中的一段(用startPos, endPos来指定) |
| 34 | + // (2) DownloadListener, 由于是多线程下载, 调用这个类的客户端不知道什么时候结束,所以你需要实现当所有 |
| 35 | + // 线程都执行完以后, 调用listener的notifiedFinished方法, 这样客户端就能收到通知。 |
| 36 | + // 具体的实现思路: |
| 37 | + // 1. 需要调用ConnectionManager的open方法打开连接, 然后通过Connection.getContentLength方法获得文件的长度 |
| 38 | + // 2. 至少启动3个线程下载, 注意每个线程需要先调用ConnectionManager的open方法 |
| 39 | + // 然后调用read方法, read方法中有读取文件的开始位置和结束位置的参数, 返回值是byte[]数组 |
| 40 | + // 3. 把byte数组写入到文件中 |
| 41 | + // 4. 所有的线程都下载完成以后, 需要调用listener的notifiedFinished方法 |
| 42 | + |
| 43 | + // 下面的代码是示例代码, 也就是说只有一个线程, 你需要改造成多线程的。 |
| 44 | + Connection conn = null; |
| 45 | + try { |
| 46 | + |
| 47 | + conn = cm.open(this.url); |
| 48 | + |
| 49 | + int length = conn.getContentLength(); |
| 50 | + |
| 51 | + new DownloadThread(conn,0,length-1).start(); |
| 52 | + |
| 53 | + } catch (ConnectionException e) { |
| 54 | + e.printStackTrace(); |
| 55 | + }finally{ |
| 56 | + if(conn != null){ |
| 57 | + conn.close(); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + public void setListener(DownloadListener listener) { |
| 67 | + this.listener = listener; |
| 68 | + } |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | + public void setConnectionManager(ConnectionManager ucm){ |
| 73 | + this.cm = ucm; |
| 74 | + } |
| 75 | + |
| 76 | + public DownloadListener getListener(){ |
| 77 | + return this.listener; |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments