天天看點

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下的多線程斷點下載下傳就隻用改下包名和路徑就可以了