多線程下載

下載:

1.得到下載文件的byte字節大小通過HttpUrlConnection--->getContentLength()

2.在本地生成一個同樣大小的文件RandomAccessFile--->setLenght();

3.多線程下載

1.得到每塊下載大小(block):getContentLength()%線程數==0?getContentLength()/線程數:getContentLength()%線程數+1

2.得到下載開始位置:block*第幾個線程

得到結束位置:(第幾個線程+1)*block-1

3.本地文件跳在開始位置去accessFile.seek(start);

4.下載

通過連接HttpUrlConnetion設置下載文件位置conn.setResponseProperties("Range","bytes=start-end");

代碼

package it.cast.app;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Downloads {
public static void main(String[] args) {
String path = "http://192.168.1.101/androidtest/td.jpg";
try {
new Downloads().download(path,3);
} catch (Exception e) {
e.printStackTrace();
}
}
public void download(String path,int threadId) throws Exception{
HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
int contentLength = conn.getContentLength();// 得到下載字節文件大小
//在本地生成同樣大小的文件
File file = new File(getFileName(path));
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
accessFile.setLength(contentLength);
int block = (contentLength % threadId == 0)?contentLength/threadId:contentLength/threadId+1;
for (int i = 0; i < threadId; i++) {
System.out.println("第"+(i+1)+"條線程已經完成");
new DownLoadThread(i,block,path,file).start();
}
}
}
private String getFileName(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
}

------

package it.cast.app;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadThread extends Thread{
private int threadId;
private int block;
private String path;
private File file;
public DownLoadThread(int threadId, int block, String path,File file) {
this.threadId = threadId;
this.block = block;
this.path = path;
this.file = file;
}
public void run() {
int start = threadId*block;//下載開始位置
int end = (threadId+1)*block-1;
try {
RandomAccessFile accessFile = new RandomAccessFile(file,"rwd");
accessFile.seek(start);
HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+start+"-"+end);
System.out.println("code="+conn.getResponseCode());
if(conn.getResponseCode() == 206){
InputStream in = conn.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len = in.read(buffer)) != -1){
accessFile.write(buffer, 0, len);
}
accessFile.close();
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章