1、基本思路是將文件分段切割、分段傳輸、分段保存。
2、分段切割用到HttpUrlConnection對(duì)象的setRequestProperty("Range", "bytes=" + start + "-" + end)方法。
3、分段傳輸用到HttpUrlConnection對(duì)象的getInputStream()方法。
4、分段保存用到RandomAccessFile的seek(int start)方法。
5、創(chuàng)建指定長(zhǎng)度的線程池,循環(huán)創(chuàng)建線程,執(zhí)行下載操作。
首先,我們要先寫(xiě)一個(gè)方法,方法的參數(shù)包含URL地址,保存的文件地址,切割后的文件開(kāi)始位置和結(jié)束位置,這樣我們就能把分段文件下載到本地。并且這個(gè)方法要是run方法,這樣我們啟動(dòng)線程時(shí)就直接執(zhí)行該方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
public class DownloadWithRange implements Runnable { private String urlLocation; private String filePath; private long start; private long end; DownloadWithRange(String urlLocation, String filePath, long start, long end) { this .urlLocation = urlLocation; this .filePath = filePath; this .start = start; this .end = end; } @Override public void run() { try { HttpURLConnection conn = getHttp(); conn.setRequestProperty( "Range" , "bytes=" + start + "-" + end); File file = new File(filePath); RandomAccessFile out = null ; if (file != null ) { out = new RandomAccessFile(file, "rwd" ); } out.seek(start); InputStream in = conn.getInputStream(); byte [] b = new byte [ 1024 ]; int len = 0 ; while ((len = in.read(b)) != - 1 ) { out.write(b, 0 , len); } in.close(); out.close(); } catch (Exception e) { e.getMessage(); } } public HttpURLConnection getHttp() throws IOException { URL url = null ; if (urlLocation != null ) { url = new URL(urlLocation); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout( 5000 ); conn.setRequestMethod( "GET" ); return conn; } } |
然后我們創(chuàng)建線程池,線程池的長(zhǎng)度可以自定義,然后循環(huán)創(chuàng)建線程來(lái)執(zhí)行請(qǐng)求,每條線程的請(qǐng)求開(kāi)始位置和結(jié)束位置都不同,本地存儲(chǔ)的文件開(kāi)始位置和請(qǐng)求開(kāi)始位置相同,這樣就可以實(shí)現(xiàn)多線程下載了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public class DownloadFileWithThreadPool { public void getFileWithThreadPool(String urlLocation,String filePath, int poolLength) throws IOException { Executor threadPool = Executors.newFixedThreadPool(poolLength); long len = getContentLength(urlLocation); for ( int i= 0 ;i<poolLength;i++) { long start=i*len/poolLength; long end = (i+ 1 )*len/poolLength- 1 ; if (i==poolLength- 1 ) { end =len; } DownloadWithRange download= new DownloadWithRange(urlLocation, filePath, start, end); threadPool.execute(download); } } public static long getContentLength(String urlLocation) throws IOException { URL url = null ; if (urlLocation != null ) { url = new URL(urlLocation); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout( 5000 ); conn.setRequestMethod( "GET" ); long len = conn.getContentLength(); return len; } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/stsinghua/p/6418796.html