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