package MutilDownLoad;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
protected static String path = "http://localhost:8080/app/dd.jpg";// 网址,这里采用本机的服务器
protected static int threadcount = 3;// 开的线程数量
public static void main(String args[]) {
//发送get请求,请求这个地址的资源
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 得到URL链接
conn.setRequestMethod("GET");// 设置GET请求
conn.setConnectTimeout(5000);// 设置请求时间
conn.setReadTimeout(5000);// 设置响应时间
if (conn.getResponseCode() == 200) {
int length = conn.getContentLength();
//设置文件的大小
File file = new File(getFileName(path));
//生成临时文件
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.setLength(length);
//计算每个线程应该下载多少个字节
int size = length / threadcount;
for (int i = 0; i < threadcount; i++) {
//计算线程下载的开始位置和结束位置
int startIndex = i * size;
int endIndex = (i + 1) * size - 1;
//如果是最后一个线程,那么位置写死
if (i == threadcount - 1) {
endIndex = length - 1;
}
MyThread t=new MyThread(startIndex, endIndex, i, path);
Thread thread=new Thread(t);
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getFileName(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
}
class MyThread implements Runnable {
int startIndex;
int endIndex;
int threadId;
String path;
public MyThread(int startIndex, int endIndex, int threadId, String path) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
this.path = path;
}
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 得到URL链接
conn.setRequestMethod("GET");// 设置GET请求
conn.setConnectTimeout(5000);// 设置请求时间
conn.setReadTimeout(5000);// 设置响应时间
//设置本次Http所请求的数据的区间
conn.setRequestProperty("Range","bytes="+startIndex+"-"+endIndex );
//请求部分数据,相应码是206
if(conn.getResponseCode()==206)
{
//流里此时只有1/3的源文件
InputStream is=conn.getInputStream();
//拿到临时文件的输出流
File file=new File("F:/dd.jpg");
RandomAccessFile raf=new RandomAccessFile(file, "rwd");
//把文件的写入位置移动到start
raf.seek(startIndex);
byte []b=new byte[1024];
int len=0;
while((len=is.read(b))!=-1)
{
raf.write(b, 0, len);
}
raf.close();
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
JAVA 多线程下载文件
最新推荐文章于 2024-05-18 15:42:48 发布