//斷點續傳和多線程下載下傳
public void httpOnLoad(String fileName,String urlpath) throws Exception
{
URL url = new URL(urlpath);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("get");
int threadSize = 3;
int fileLength = conn.getContentLength();
int block = fileLength/3+1;
conn.disconnect();
File file = new File(fileName);
RandomAccessFile randomFile = new RandomAccessFile(file,"RW");
randomFile.setLength(fileLength);
randomFile.close();
for(int i = 0;i<3;i++){
int startPosition = i * block;//從網絡檔案的什麼位置開始下載下傳
RandomAccessFile threadFile = new RandomAccessFile(file,"RW");
threadFile.seek(startPosition);
new DownLoadThread(url,startPosition,threadFile,block).start();
}
}
private class DownLoadThread extends Thread{
URL url;
int startPosition;
RandomAccessFile threadFile;
int block;
public DownLoadThread(URL url,int startPosition,RandomAccessFile threadFile,int block){
this.url = url;
this.startPosition = startPosition;
this.threadFile = threadFile;
this.block = block;
}
@Override
public void run() {
super.run();
HttpURLConnection con;
try {
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("get");
con.setRequestProperty("Range", "betys"+startPosition+"-");
con.setReadTimeout(6000);
InputStream inputStream = con.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
int readFileSize = 0;
while(readFileSize <= block && (len = inputStream.read(buffer))!=-1){
threadFile.write(buffer,0,len);
readFileSize+=len;//累計下載下傳檔案大小
}
threadFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}