import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class DownLoad {
static int threadCount = 3;
static String path = "http://127.0.0.1/test.avi";
public static void main(String[] args) {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
int len = conn.getContentLength();
int size = len / threadCount;
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(len);
for (int i = 0; i < threadCount; i++) {
int startIndex = i * size;
int endIndex = (i + 1) * size - 1;
if (i == threadCount - 1) {
endIndex = len - 1;
}
System.out.println("线程" + i + "," + startIndex + "--->" + endIndex);
new MyThread(i, size, startIndex, endIndex).start();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
static class MyThread extends Thread {
@Override
public void run() {
try {
int total = startIndex;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
if (conn.getResponseCode() == 206) {
InputStream is = conn.getInputStream();
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(startIndex);
int len = 0;
byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
total +=len;
System.out.println("线程" + threadNum + "----->已下载" + total);
raf.write(b, 0, len);
}
raf.close();
System.out.println("线程" + threadNum + "下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
int size;
int startIndex;
int endIndex;
int threadNum;
public MyThread(int threadNum, int size, int startIndex, int endIndex) {
super();
this.size = size;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadNum = threadNum;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getEndIndex() {
return endIndex;
}
public void setEndIndex(int endIndex) {
this.endIndex = endIndex;
}
public MyThread(int size, int startIndex, int endIndex) {
this.size = size;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public MyThread() {
}
}
}