关于多线程网络文件下载
package com.softeem.thread;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 完成一个多线程断点下载工具
* 1.通过提供的网络文件地址,下载该文件
* 2.要求使用多个线程同时下载,
* 3.实时更新下载进度(0%~100%)
* 4.要求能够实现断点功能(扩展)
*/
public class ThreadNetFileCopy extends Thread{
private String sourceURL; // 下载源的位置URL
private File target;// 保存到本地的目标文件
private long start; // 当前线程拷贝的开始位置
private long end; // 当前线程拷贝的结束位置
public long current = 0;
public ThreadNetFileCopy(String sourceURL, File target, long start, long end) {
super();
this.sourceURL = sourceURL;
this.target = target;
this.start = start;
this.end = end;
}
@Override
public void run() {
InputStream is = null;
RandomAccessFile rsf = null;
URL url = null;
try {
url = new URL(sourceURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(10000);
int code = conn.getResponseCode();
System.out.println(Thread.currentThread().getName()+"开始拷贝...");
if(code == HttpURLConnection.HTTP_OK){
is = conn.getInputStream();
rsf = new RandomAccessFile(target, "rw");
is.skip(start); // 如何将源URL的文件分为四段
rsf.seek(start);// seek到段点的位置,分段拷贝
byte[] b = new byte[1024];
int length = 0;
while((length = is.read(b)) != -1 && current <= (end - start)){
current += length; // 记录当前进程已下载的总字节数
rsf.write(b, 0, length);
}
}
System.out.println("完成拷贝");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(rsf != null) rsf.close();
if(is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException{
String sourceURL = "http://192.168.46.254:8888/easyBuy/images/plmm.jpg";
String sourceName = sourceURL.substring(sourceURL.lastIndexOf("/"));
File target = new File("D:\\", sourceName);
URL url = new URL(sourceURL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// 实时更新下载进度
long item = conn.getContentLengthLong()/4;
for(int i = 0; i < 4; i++){
new ThreadNetFileCopy(sourceURL, target, i*item, (i+1)*item).start();
}
}
}