-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDownloadBlock.java
79 lines (62 loc) · 1.87 KB
/
DownloadBlock.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public final class DownloadBlock implements Runnable {
public DownloadBlock(int index, int startPosition, int endPosition,
String urlLink, String localPath) {
this.index = index;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.urlLink = urlLink;
this.localPath = localPath;
}
private final int index;
private final int startPosition;
private final int endPosition;
private final String urlLink;
private final String localPath;
private HttpURLConnection connection;
private RandomAccessFile randomAccessFile;
private static int BYTES_READ = 0;
/**
* Max download speed...1MB/s
*/
private static final int BUFFER_SIZE = 1024;
public static int getBytesRead() {
return BYTES_READ;
}
public int getIndex() {
return index;
}
private void initiateConnection() throws IOException {
connection = (HttpURLConnection) (new URL(urlLink).openConnection());
connection.addRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition);
connection.connect();
randomAccessFile = new RandomAccessFile(localPath, "rw");
randomAccessFile.seek(startPosition);
}
@Override
public void run() {
try {
initiateConnection();
} catch (IOException e) {
e.printStackTrace();
return;
}
final byte[] buffer = new byte[BUFFER_SIZE];
int currentBytes;
try {
final InputStream inputStream = connection.getInputStream();
while ((currentBytes = inputStream.read(buffer)) != -1) {
randomAccessFile.write(buffer, 0, currentBytes);
BYTES_READ += currentBytes;
}
inputStream.close();
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}