package com.heima.javadownload;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class ThreadDownLoad {
private static int blockSize = 3000000;
private static String path;
public static void main(String[] args) {
path = "http://188.188.1.10:8080/DownLoadServlet/huoshaodejimo.flac";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
int length = conn.getContentLength();
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(length);
raf.close();
int threadCount = length / blockSize + 1;
for (int threadID = 0; threadID < threadCount; threadID++) {
int startIndex = threadID * blockSize;
int endIndex = (threadID + 1) * blockSize - 1;
if (threadID == threadCount - 1) {
endIndex = length - 1;
}
new Thread(new MyTask(threadID, startIndex, endIndex)).start();
System.out.println(threadID + "开始下载");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class MyTask implements Runnable {
private int threadID;
private int startIndex;
private int endIndex;
private int currentPosition;
public MyTask(int threadID, int startIndex, int endIndex) {
super();
this.threadID = threadID;
this.startIndex = startIndex;
this.endIndex = endIndex;
this.currentPosition = startIndex;
}
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
File file = new File(getFileName(path));
RandomAccessFile raf = new RandomAccessFile(file, "rw");
conn.setRequestProperty("range", "bytes=" + startIndex + "-" + endIndex);
raf.seek(startIndex);
if (conn.getResponseCode() == 206) {
InputStream inputStream = conn.getInputStream();
byte[] arr = new byte[8192];
int len;
while ((len = inputStream.read(arr)) != -1) {
raf.write(arr, 0, len);
}
raf.close();
inputStream.close();
}
System.out.println(threadID + "结束下载");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static String getFileName(String path) {
return path.substring(path.lastIndexOf("/") + 1);
}
} |
|