我剛聽到斷點(diǎn)續(xù)傳佣谐,感覺好高端的樣子,因?yàn)閺膩頉]聽說過這個(gè)名詞猖毫,但是看了別人的博客之后台谍,發(fā)現(xiàn),實(shí)現(xiàn)斷點(diǎn)續(xù)傳的功能并沒有想象中的那么復(fù)雜吁断。
在做斷點(diǎn)續(xù)傳之前趁蕊,我們可以先來看下普通的文件下載功能是怎么實(shí)現(xiàn)的,普通的文件下載功能實(shí)現(xiàn)起來是很簡單的仔役,代碼如下:
URL url = null;
HttpURLConnection httpURLConnection = null;
BufferedInputStream bufferedReader;
try {
url = new URL(downloadUrl);
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setUseCaches(false); // 請求時(shí)不使用緩存
httpURLConnection.setConnectTimeout(5 * 1000); // 設(shè)置連接超時(shí)時(shí)間
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
int bufferSize = 1024;
bufferedReader = new BufferedInputStream(httpURLConnection.getInputStream(),bufferSize); //為InputStream類增加緩沖區(qū)功能
int len = 0; //讀取到的數(shù)據(jù)長度
byte[] buffer = new byte[bufferSize];
//寫入中間文件
mOutputStream = new FileOutputStream(mTempFile,true);//true表示向打開的文件末尾追加數(shù)據(jù)
mByteOutput = new ByteArrayOutputStream();
//開始讀取
while((len = bufferedReader.read(buffer)) != -1) {
mByteOutput.write(buffer,0,len);
}
mByteOutput.close();
bufferedReader.close();
}catch (MalformedURLException malformedURLException){
malformedURLException.printStackTrace();
}catch (IOException ioException){
ioException.printStackTrace();
}finally {
if(httpURLConnection!=null){
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
使用以上這些代碼就可以實(shí)現(xiàn)普通的文件下載功能掷伙。
如果用戶在下載的過程中突然想暫停下載,那么又兵,上面的那段代碼就不能滿足需求了任柜,這個(gè)時(shí)候就有了斷點(diǎn)續(xù)傳的概念了。斷點(diǎn)續(xù)傳的概念簡單來說就是在下載的過程中暫停沛厨,繼續(xù)下載時(shí)接著上一次的進(jìn)度繼續(xù)下載宙地,直到下載完成。
現(xiàn)在逆皮,我們來說下斷點(diǎn)續(xù)傳的原理宅粥,斷點(diǎn)續(xù)傳的原理其實(shí)也很簡單,從上面那段代碼我們可以知道电谣,文件的下載過程其實(shí)就是字節(jié)的讀取和寫入的過程秽梅,而斷點(diǎn)續(xù)傳抹蚀,就是在字節(jié)讀取過程中停止之后,又能接著上次的進(jìn)度繼續(xù)讀取字節(jié)企垦。那我們要實(shí)現(xiàn)這個(gè)功能环壤,就需要在每次讀取字節(jié)時(shí)記錄讀取的字節(jié),然后在繼續(xù)下載的時(shí)候繼續(xù)上次的字節(jié)讀取钞诡。
那么具體怎么來實(shí)現(xiàn)這個(gè)功能呢郑现?其實(shí)很簡單,只需要使用這幾行代碼就能實(shí)現(xiàn):
首先在字節(jié)讀取的地方加上字節(jié)長度的記錄:
while((len = bufferedReader.read(buffer)) != -1) {
mByteOutput.write(buffer,0,len);
mLoadedByteLength += mByteOutput.size();
}
然后在發(fā)起下載請求的時(shí)候加上這行代碼:
if(mLoadedByteLength > 0 && mLoadedByteLength < mTotalByteLength){
httpURLConnection.setRequestProperty("Range", "bytes=" + mLoadedByteLength + "-");
}
這樣就能實(shí)現(xiàn)斷點(diǎn)續(xù)傳的功能臭增,看完這些是不是感覺很簡單啊懂酱。
效果圖如下:
最后添上自己做的一個(gè)斷點(diǎn)續(xù)傳的小demo的github地址,這個(gè)demo或許存在著bug誊抛,不過這不重要列牺,這個(gè)小demo主要目的就是為大家實(shí)現(xiàn)斷點(diǎn)續(xù)傳功能做參考。
https://github.com/fm183/DownloadFilePorject.git