多线程下载

来源:互联网 发布:常见20网络诈骗 编辑:程序博客网 时间:2024/06/16 01:51
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class MutilDownLoad {


public static void main(String[] args) throws Exception {
int threadCount = 3;
int blockSize;

URL url = new URL("http://10.1.2.90:8080/apache-maven-3.3.9-bin.zip");


HttpURLConnection connection = (HttpURLConnection) url.openConnection();


connection.setReadTimeout(5000);
connection.setRequestMethod("GET");


if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 获取大小
int length = connection.getContentLength();
// 申请控件
RandomAccessFile raf = new RandomAccessFile(
"D://apache-maven-3.3.9-bin.zip", "rw");


raf.setLength(length);


raf.close();


blockSize = length / threadCount;
// 计算偏移量以及块大小
for (int i = 1; i <= threadCount; i++) {


int startIndex = (i - 1) * blockSize;
int endIndex = i * blockSize - 1;


if (i == threadCount) {
endIndex = length;
}



new MutilDownLoad().startMutilDownLoad(startIndex , endIndex);
}


}
}

public  void startMutilDownLoad(final int startIndex,final int endIndex){
new Thread() {
public void run() {
URL url;
try {
url = new URL(
"http://10.1.2.90:8080/apache-maven-3.3.9-bin.zip");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();


connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");



connection.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);

if(connection.getResponseCode() == 206){
       InputStream is = connection.getInputStream();
       RandomAccessFile raf = new RandomAccessFile("D://apache-maven-3.3.9-bin.zip", "rwd");
       //指定从哪个位置开始存放数据
       raf.seek(startIndex);
       byte[] b = new byte[1024];
       int len;
       while((len = is.read(b)) != -1){
           raf.write(b, 0, len);
       }
       raf.close();
   }

System.out.println(Thread.currentThread().getId() + "下载完成");
} catch (Exception e) {
e.printStackTrace();
}


};
}.start();
}
}
0 0