1 package cn.test.DownLoad;
2
3 import java.io.File;
4 import java.io.InputStream;
5 import java.io.RandomAccessFile;
6 import java.net.HttpURLConnection;
7 import java.net.URL;
8
9 public class MultiPart {
10 public void down() throws Exception
11 {
12 //1、声明URL
13 String fileName="a.rar";
14 String path="http://localhost:8080/day23_MultiThreadDownLoad/file/"+fileName;
15 URL url=new URL(path);
16 //2、返回连接对象
17 HttpURLConnection conn=(HttpURLConnection) url.openConnection();
18 //3、设置请求类型
19 conn.setRequestMethod("GET");
20 //4、设置允许接收消息
21 conn.setDoInput(true);
22 //5、连接
23 conn.connect();
24 //6、状态码
25 int code=conn.getResponseCode();
26 if(code==200)
27 {
28 int sum=conn.getContentLength();//总长度
29 String downFile="d:\\"+fileName;
30 //7、创建一个相同大小的空文件
31 RandomAccessFile file=new RandomAccessFile(new File(downFile), "rw");
32 file.setLength(sum);
33 file.close();
34 //8、声明线程数量
35 int threadCount=3;
36 //9、声明每个线程的下载量
37 int threadSize=sum/threadCount+((sum%threadCount==0)?0:1);
38 for(int i=0;i<threadCount;i++)
39 {
40 int start=i*threadSize;
41 int end=start+threadSize-1;
42 System.out.println("线程: "+i+" : "+start+" : "+end);
43 //10、启动线程
44 new myThread(start,end,downFile,url).start();
45 }
46 }
47 //11、关闭连接
48 conn.disconnect();
49 }
50
51 public static void main(String[] args) {
52 try {
53 new MultiPart().down();
54 } catch (Exception e) {
55 e.printStackTrace();
56 }
57 System.out.println("OK");
58 }
59 }
60
61 class myThread extends Thread
62 {
63 private int start;
64 private int end;
65 private String downFile;
66 private URL url;
67 public myThread(int start, int end, String downFile, URL url) {
68 this.start = start;
69 this.end = end;
70 this.downFile = downFile;
71 this.url = url;
72 }
73
74 public void run() {
75 try {
76 HttpURLConnection conn=(HttpURLConnection) url.openConnection();
77 conn.setRequestMethod("GET");
78 conn.setDoInput(true);
79 //设置从哪里下载。断点
80 conn.setRequestProperty("range", "bytes="+start+"-"+end);
81 conn.connect();
82 int code=conn.getResponseCode();
83 if(code==206)
84 {
85 int size=conn.getContentLength();
86 InputStream in=conn.getInputStream();
87 //写同一文件
88 RandomAccessFile file=new RandomAccessFile(new File(downFile), "rw");
89 //设置从文件的哪里开始写
90 file.seek(start);
91 byte[] b=new byte[1024];
92 int len=-1;
93 while((len=in.read(b))!=-1)
94 {
95 file.write(b, 0, len);
96 }
97 file.close();
98 }
99 conn.disconnect();
100
101 } catch (Exception e) {
102 e.printStackTrace();
103 }
104 }
105 }