标签:java 多线程 下载
package com.download;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MutileThreadDown {
private static int blockCount=3;
private static int blockSize;
public static void main(String[] args) throws Exception{
String path="http://localhost:8080/Web025Server/media/bootstrap.avi";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
int responseCode=conn.getResponseCode();
if(responseCode==200){
int size=conn.getContentLength();
System.out.println("服务器端的长度"+size);
blockSize=size/blockCount;
//创建一个跟服务器端大小相同的空白文件
File file=new File("aa.avi");
RandomAccessFile raf=new RandomAccessFile(file,"rw");
raf.setLength(size);//设置文件的的大小
//2.开启若干个子线程,分别下载资源
for(int i=1;i<=blockCount;i++){
int startIndex=(i-1)*blockSize+0;
int endIndex=i*blockSize-1;
if(i==blockCount){
endIndex=size-1;
}
new DownLoadThread(startIndex, endIndex, i, path).start();;
System.out.println("开启线程"+i+"开始的位置"+startIndex+"结束的位置是"+endIndex);
}
}
conn.disconnect();
}
//定义一个线程的内部类
private static class DownLoadThread extends Thread{
private int startIndex;
private int endIndex;
private int threadi;
private String path;
public DownLoadThread(int startIndex, int endIndex, int threadi,
String path) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadi = threadi;
this.path = path;
}
@Override
public void run() {
try {
String path="http://localhost:8080/Web025Server/media/bootstrap.avi";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
conn.setConnectTimeout(10000);
conn.setReadTimeout(5000);
int responseCode=conn.getResponseCode();
System.out.println("服务器的响应码"+responseCode);
//创建一个跟服务器端大小相同的空白文件
File file=new File("aa.avi");
RandomAccessFile raf=new RandomAccessFile(file,"rw");
InputStream in=conn.getInputStream();
raf.seek(startIndex);//从哪个位置开始写文件
int len=-1;
byte[] bytes=new byte[1024];
while((len=in.read(bytes))!=-1){
raf.write(bytes, 0, len);
}
in.close();
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}本文出自 “Java大白的战地” 博客,请务必保留此出处http://8023java.blog.51cto.com/10117207/1670663
标签:java 多线程 下载
原文地址:http://8023java.blog.51cto.com/10117207/1670663