package xiawenquan.com;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 多线程下载
* @author xiawenquan
*
*/
public class MyDownLoad {
public static void main(String[] args) {
String path = "http://gb.cri.cn/mmsource/images/2011/10/22/a817ae91a2bb48e59c40673a9694b5fb.jpg";
new MyDownLoad().download(path,3);
}
/**
* 根据路径和线程数下载文件
* @param path
* @param threadSize
*/
private void download(String path, int threadSize) {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(60*1000);
connection.setRequestMethod("GET");
if(connection.getResponseCode() == 200){
int fileLength = connection.getContentLength();
File file = new File(getFileNameByPath(path));
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(fileLength);
accessFile.close();
// 计算每条线程下载的数据量,如果不整除则加上1
int block = fileLength / threadSize == 0 ? fileLength / threadSize : fileLength / threadSize + 1;
for(int threadid = 0; threadid < threadSize; threadid ++){
new DownLoad(threadid,block,url,file).start();
}
}else{
System.out.println("下载失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据路径获取文件名称
* @param path
* @return
*/
private String getFileNameByPath(String path) {
String fileName = path.substring(path.lastIndexOf("/" ) + 1);
return fileName;
}
// 负责下载的线程类
private class DownLoad extends Thread{
private int threadid;
private int block;
private URL url;
private File file;
public DownLoad(int threadid, int block, URL url, File file) {
this.threadid = threadid;
this.block = block;
this.url = url;
this.file = file;
}
@Override
public void run() { // TODO 这个run()是每个线程下载的代码
try {
int start = threadid * block ; // 计算线程下载的开始位置
int end = (threadid + 1) * block - 1;// 计算线程下载的结束位置
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.seek(start); // seek()是使每一条线程在本地文件file中的什么位置开始写入数据
// 然后每条线程去连网
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(60*1000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Range", "bytes=" + start + "-" + end );
if(connection.getResponseCode() == 206){ // 分段下载的返回码不是200,而是206
InputStream inputStream = connection.getInputStream(); // 获取网络返回来的数据,返回来的数据是每一条线程的下载的数据
byte buffer[] = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
accessFile.write(buffer, 0, len);
}
accessFile.close();
inputStream.close();
System.out.println("第" + (threadid + 1) + "条线程下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
java android 多线程下载
最新推荐文章于 2022-03-16 09:16:00 发布