您的位置:首页 > 编程语言 > Java开发

Java实现多线程下载

2014-12-11 18:38 302 查看
package cn.test.DownLoad;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiPart {
public void down() throws Exception
{
//1、声明URL
String fileName="a.rar";
String path="http://localhost:8080/day23_MultiThreadDownLoad/file/"+fileName;
URL url=new URL(path);
//2、返回连接对象
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
//3、设置请求类型
conn.setRequestMethod("GET");
//4、设置允许接收消息
conn.setDoInput(true);
//5、连接
conn.connect();
//6、状态码
int code=conn.getResponseCode();
if(code==200)
{
int sum=conn.getContentLength();//总长度
String downFile="d:\\"+fileName;
//7、创建一个相同大小的空文件
RandomAccessFile file=new RandomAccessFile(new File(downFile), "rw");
file.setLength(sum);
file.close();
//8、声明线程数量
int threadCount=3;
//9、声明每个线程的下载量
int threadSize=sum/threadCount+((sum%threadCount==0)?0:1);
for(int i=0;i<threadCount;i++)
{
int start=i*threadSize;
int end=start+threadSize-1;
System.out.println("线程: "+i+" : "+start+" : "+end);
//10、启动线程
new myThread(start,end,downFile,url).start();
}
}
//11、关闭连接
conn.disconnect();
}

public static void main(String[] args) {
try {
new MultiPart().down();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("OK");
}
}

class myThread extends Thread
{
private int start;
private int end;
private String downFile;
private URL url;
public myThread(int start, int end, String downFile, URL url) {
this.start = start;
this.end = end;
this.downFile = downFile;
this.url = url;
}

public void run() {
try {
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
//设置从哪里下载。断点
conn.setRequestProperty("range", "bytes="+start+"-"+end);
conn.connect();
int code=conn.getResponseCode();
if(code==206)
{
int size=conn.getContentLength();
InputStream in=conn.getInputStream();
//写同一文件
RandomAccessFile file=new RandomAccessFile(new File(downFile), "rw");
//设置从文件的哪里开始写
file.seek(start);
byte[] b=new byte[1024];
int len=-1;
while((len=in.read(b))!=-1)
{
file.write(b, 0, len);
}
file.close();
}
conn.disconnect();

} catch (Exception e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: