javase的多線程斷點下載

-----------------------斷點下載---------------------------
>DownloadThread extends Thread
//線程id
private int threadid;
private int startposition;
private int endposition;

DownloadThread(int ,int,int){
構造方法
}
run{
//斷點下載之:判斷是否已經下載過一部分的數據*********
File finfo = new File(threadid+".txt");
if(finfo.exists()&&finfo.length()>0){
FileInputReader fis = new FileInputStream(finfo);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String lastposition = br.readLine();
//這個現場上一次下載的大小
int intlastposition= Integer.parseInt(lastposition );
startPosition+=intlastposition;
fis.close();
}




URl url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.opneConnection();
conn.setRequestMethod("GET");
conn.setRequestPropertu("Range","bytes="+startPositeion+"-"+endPosition);
//從服務器下載資源
int code = conn.getResponseCode();//206 請求部分數據成功
if(code==206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");
//☆非常重要指定文件寫的位置
raf.seek(startPosition);
byte[] buffer = new byte[1024*1024];//緩存區變成 1MB,緩存區越大,對硬盤的損耗就越小
int len = -1;
int total = 0;//當期線程這一次下載了多少
while((len=is.read(buffer))!=-1){
raf.write(buffer,0,len);
//斷點下載之:把當期下載位置記錄下來**************
total+=len;
RandomAccessFile inforaf = new RandomAccessFile(threadid+".txt","rwd");//每一次 數據都被同步到底 //層硬盤
inforaf.write(String.valueof(startposition+total).getBytes());
inforaf.close();
}
is.close();
raf.close():
syso("線程:"+threadid+"下載完畢了......");
}
}


>因爲多線程分配是隨機的,那麼如何判斷什麼時候多線程下載完畢了呢
1.定義一個全局變量,一個標記位
1.private int runningThreadCount;
2.在線程循環是將其賦值爲0,初始化
3.在拋出的異常//這裏頭要加一個同步鎖
finally{
synchronize(MultiDownloader.class){
runningThreadCount--;
if(runningThreadCount<=0){
syso("多線程下載完畢了...恭喜恭喜");
}
}
}//從服務器下載資源
int code = conn.getResponseCode();//206 請求部分數據成功
if(code==206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile("temp.exe","rw");
//☆非常重要指定文件寫的位置
raf.seek(startPosition);
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1){
raf.write(buffer,0,len);
//把當期下載位置記錄下來
}
is.close();
raf.close():
syso("線程:"+threadid+"下載完畢了......");
}
}


--------------------------------------------------
優化:
1.根據路徑獲取文件名
public static String getDownLoadFileName(String path){
return path.substring(path.lastIndexof("/")+1);
}
2.對下載完成的文件將,記錄日誌給刪除
for(int i=0;i<totalThreadCount;++i){
File f = new File(totalThreadCount+getDownLooadFileName(path)+i+".txt");
f.delete();

}


-----------------------------------------------------

ps:那這個javase的多線程斷點下載敲會後,android下的多線程斷點下載就只用改下包名和路徑就可以了

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