文件长度" + fileLength);
size = fileLength / threadCount;
System.out.println("每个下载量==" + size);
conn.disconnect();// 断开链接
}
public URL getFileUrl() {
return fileUrl;
public int getThreadCount() {
return this.threadCount;
/**
* 开始下载
*/
public void startDown() {
for (int i = 0; i < threadCount; i++) {
try {
RandomAccessFile raFile = new RandomAccessFile(pathName, "rw");
tDownthreads[i] = new Downthread(i * size, raFile, i);
tDownthreads[i].start();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
* 下载线程类
*
* @author luweicheng
class Downthread extends Thread {
private int startPos;// 开始的位置
private InputStream is;
private RandomAccessFile raFile;
private int length;// 下载的文件长度
private int flag;// 线程标志
public Downthread(int startPos, RandomAccessFile raFile, int i) {
this.startPos = startPos;
this.raFile = raFile;
flag = i;
@Override
public void run() {
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("connection", "keep-alive");
connection.setConnectTimeout(5 * 1000);
is = connection.getInputStream();
is.skip(startPos);
raFile.seek(startPos);
byte[] buf = new byte[8 * 1024];
int hasread = 0;// 读出的字节数
// 将位置在 startPos - startPos 位置的数据读出写入
while (length < size && (hasread = is.read(buf)) != -1) {
raFile.write(buf, 0, hasread);
length += hasread;
System.out.println("*****线程" + flag + "下载了*********" + length);
}
System.out.println("*******线程" + flag + "下载完成*********");
} catch (IOException e) {
} finally {
try {
is.close();
raFile.close();
} catch (IOException e) {
e.printStackTrace();
}
效果展示:
