-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadDownload.java
More file actions
49 lines (45 loc) · 954 Bytes
/
ThreadDownload.java
File metadata and controls
49 lines (45 loc) · 954 Bytes
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
import java.net.URL;
import java.io.*;
class ThreadDownload
{
public static void main(String[] args)
throws IOException
{
final URL[] urls = {
new URL("http://www.pku.edu.cn"),
new URL("http://www.baidu.com"),
new URL("http://www.sina.com.cn"),
new URL("http://www.dstang.com")
};
final String[] files = {
"pku.htm",
"baidu.htm",
"sina.htm",
"study.htm",
};
for(int i=0; i<urls.length; i++){
final int idx = i;
new Thread( ()-> {
try{
System.out.println( urls[idx] );
download( urls[idx], files[idx]);
}catch(Exception ex){
ex.printStackTrace();
}
}).start();
}
}
static void download( URL url, String file)
throws IOException
{
try(InputStream input = url.openStream();
OutputStream output = new FileOutputStream(file))
{
byte[] data = new byte[1024];
int length;
while((length=input.read(data))!=-1){
output.write(data,0,length);
}
}
}
}