PC版與Android手機(jī)版帶斷點(diǎn)續(xù)傳的多線程下載
一、多線程下載
多線程下載就是搶占服務(wù)器資源
原理:服務(wù)器CPU 分配給每條線程的時(shí)間片相同,服務(wù)器帶寬平均分配給每條線程,所以客戶端開(kāi)啟的線程越多,就能搶占到更多的服務(wù)器資源。
1、設(shè)置開(kāi)啟線程數(shù),發(fā)送http請(qǐng)求到下載地址,獲取下載文件的總長(zhǎng)度
然后創(chuàng)建一個(gè)長(zhǎng)度一致的臨時(shí)文件,避免下載到一半存儲(chǔ)空間不夠了,并計(jì)算每個(gè)線程下載多少數(shù)據(jù)
2、計(jì)算每個(gè)線程下載數(shù)據(jù)的開(kāi)始和結(jié)束位置
再次發(fā)送請(qǐng)求,用 Range 頭請(qǐng)求開(kāi)始位置和結(jié)束位置的數(shù)據(jù)
3、將下載到的數(shù)據(jù),存放至臨時(shí)文件中
4、帶斷點(diǎn)續(xù)傳的多線程下載
定義一個(gè)int變量,記錄每條線程下載的數(shù)據(jù)總長(zhǎng)度,然后加上該線程的下載開(kāi)始位置,得到的結(jié)果就是下次下載時(shí),該線程的開(kāi)始位置,把得到的結(jié)果存入緩存文件,當(dāng)文件下載完成,刪除臨時(shí)進(jìn)度文件。
public class MultiDownload {
static int ThreadCount = ;
static int finishedThread = ;
//確定下載地址
static String filename = "EditPlus.exe";
static String path = "http://...:/"+filename;
public static void main(String[] args) {
//、發(fā)送get請(qǐng)求,去獲得下載文件的長(zhǎng)度
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout();
conn.setReadTimeout();
if (conn.getResponseCode()==) {
//如果請(qǐng)求成功,拿到所請(qǐng)求資源文件的長(zhǎng)度
int length = conn.getContentLength();
//、生成一個(gè)與原文件同樣的大小的臨時(shí)文件,以免下載一半存儲(chǔ)空間不夠了
File file = new File(filename);//演示,所以將保存的文件目錄放在工程的同目錄
//使用RandomAccessFile 生成臨時(shí)文件,可以用指針定位文件的任意位置,
//而且能夠?qū)崟r(shí)寫到硬件底層設(shè)備,略過(guò)緩存,這對(duì)下載文件是突然斷電等意外是有好處的
RandomAccessFile raf = new RandomAccessFile(file, "rwd");//rwd, 實(shí)時(shí)寫到底層設(shè)備
//設(shè)置臨時(shí)文件的大小
raf.setLength(length);
raf.close();
//、計(jì)算出每個(gè)線程應(yīng)該下載多少個(gè)字節(jié)
int size = length/ThreadCount;//如果有余數(shù),負(fù)責(zé)最后一部分的線程負(fù)責(zé)下砸
//開(kāi)啟多線程
for (int threadId = ; threadId < ThreadCount; threadId++) {
//計(jì)算每個(gè)線程下載的開(kāi)始位置和結(jié)束位置
int startIndex = threadId*size; // 開(kāi)始 = 線程id * size
int endIndex = (threadId+)*size - ; //結(jié)束 = (線程id + )*size -
//如果是最后一個(gè)線程,那么結(jié)束位置寫死為文件結(jié)束位置
if (threadId == ThreadCount - ) {
endIndex = length - ;
}
//System.out.println("線程"+threadId+"的下載區(qū)間是: "+startIndex+"----"+endIndex);
new DownloadThread(startIndex,endIndex,threadId).start();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DownloadThread extends Thread{
private int startIndex;
private int endIndex;
private int threadId;
public DownloadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
public void run() {
//每個(gè)線程再次發(fā)送http請(qǐng)求,下載自己對(duì)應(yīng)的那部分?jǐn)?shù)據(jù)
try {
File progressFile = new File(threadId+".txt");
//判斷進(jìn)度文件是否存在,如果存在,則接著斷點(diǎn)繼續(xù)下載,如果不存在,則從頭下載
if (progressFile.exists()) {
FileInputStream fis = new FileInputStream(progressFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
//從進(jìn)度文件中度取出上一次下載的總進(jìn)度,然后與原本的開(kāi)始進(jìn)度相加,得到新的開(kāi)始進(jìn)度
startIndex += Integer.parseInt(br.readLine());
fis.close();
}
System.out.println("線程"+threadId+"的下載區(qū)間是:"+startIndex+"----"+endIndex);
//、每個(gè)線程發(fā)送http請(qǐng)求自己的數(shù)據(jù)
URL url = new URL(MultiDownload.path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout();
conn.setReadTimeout();
//設(shè)置本次http請(qǐng)求所請(qǐng)求的數(shù)據(jù)的區(qū)間
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
//請(qǐng)求部分?jǐn)?shù)據(jù),響應(yīng)碼是
if (conn.getResponseCode()==) {
//此時(shí),流里只有ThreadCount分之一的原文件數(shù)據(jù)
InputStream is = conn.getInputStream();
byte[] b = new byte[];
int len = ;
int total = ;//total 用于保存斷點(diǎn)續(xù)傳的斷點(diǎn)
//拿到臨時(shí)文件的輸出流
File file = new File(MultiDownload.filename);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
//把文件的寫入位置移動(dòng)至 startIndex
raf.seek(startIndex);
while ((len = is.read(b))!=-) {
//每次讀取流里數(shù)據(jù)之后,同步把數(shù)據(jù)寫入臨時(shí)文件
raf.write(b, , len);
total += len;
//System.out.println("線程" + threadId + "下載了" + total);
//生成一個(gè)一個(gè)專門用來(lái)記錄下載進(jìn)度的臨時(shí)文件
RandomAccessFile progressRaf = new RandomAccessFile(progressFile, "rwd");
progressRaf.write((total+"").getBytes());
progressRaf.close();
}
System.out.println("線程"+threadId+"下載完了---------------------");
raf.close();
//當(dāng)所有的線程下載完之后,將進(jìn)度文件刪除
MultiDownload.finishedThread++;
synchronized (MultiDownload.path) {//所有線程使用同一個(gè)鎖
if (MultiDownload.finishedThread==MultiDownload.ThreadCount) {
for (int i = ; i < MultiDownload.ThreadCount; i++) {
File f = new File(i+".txt");
f.delete();
}
MultiDownload.finishedThread=;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、Android手機(jī)版帶斷點(diǎn)續(xù)傳的多線程下載
Android手機(jī)版的帶斷點(diǎn)續(xù)傳的多線程下載邏輯與PC版的幾乎一樣,只不過(guò)在Android手機(jī)中耗時(shí)操作不能放在主線程,網(wǎng)絡(luò)下載屬于耗時(shí)操作,所以多線程下載要在Android中開(kāi)啟一個(gè)子線程執(zhí)行。并使用消息隊(duì)列機(jī)制刷新文本進(jìn)度條。
public class MainActivity extends Activity {
static int ThreadCount = ;
static int FinishedThread = ;
int currentProgess;
static String Filename = "QQPlayer.exe";
static String Path = "http://...:/"+Filename;
static MainActivity ma;
static ProgressBar pb;
static TextView tv;
static Handler handler = new Handler(){
public void handleMessage(android.os.Message msg){
tv.setText((long)pb.getProgress()* /pb.getMax() +"%");
};
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ma = this;
pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv);
}
public void download(View v){
Thread t = new Thread(){
public void run() {
//發(fā)送http請(qǐng)求獲取文件的長(zhǎng)度,創(chuàng)建臨時(shí)文件
try {
URL url= new URL(Path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout();
conn.setReadTimeout();
if (conn.getResponseCode()==) {
int length = conn.getContentLength();
//設(shè)置進(jìn)度條的最大值就是原文件的總長(zhǎng)度
pb.setMax(length);
//生成一個(gè)與原文件相同大小的臨時(shí)文件
File file = new File(Environment.getExternalStorageDirectory(),Filename);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.setLength(length);
raf.close();
//計(jì)算每個(gè)線程需要下載的數(shù)據(jù)大小
int size = length/ThreadCount;
//開(kāi)啟多線程
for (int threadId = ; threadId < ThreadCount; threadId++) {
int startIndex = threadId*size;
int endIndex = (threadId + )*size - ;
if (threadId==ThreadCount - ) {
endIndex = length - ;
}
new DownloadThread(startIndex, endIndex, threadId).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
class DownloadThread extends Thread{
private int startIndex;
private int endIndex;
private int threadId;
public DownloadThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
public void run() {
// 每個(gè)線程發(fā)送http請(qǐng)求自己的數(shù)據(jù)
try{
//先判斷是不是斷點(diǎn)續(xù)傳
File progessFile = new File(Environment.getExternalStorageDirectory(),threadId+".txt");
if (progessFile.exists()) {
FileReader fr = new FileReader(progessFile);
BufferedReader br = new BufferedReader(fr);
int lastProgess = Integer.parseInt(br.readLine());
startIndex += lastProgess;
//把上次下載的進(jìn)度顯示至進(jìn)度條
currentProgess +=lastProgess;
pb.setProgress(currentProgess);
//發(fā)消息,讓主線程刷新文本進(jìn)度
handler.sendEmptyMessage();
br.close();
fr.close();
}
URL url = new URL(Path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout();
conn.setReadTimeout();
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
if (conn.getResponseCode()==) {
InputStream is = conn.getInputStream();
byte[] buffer = new byte[];
int len = ;
int total = ;
File file = new File(Environment.getExternalStorageDirectory(),Filename);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(startIndex);
while ((len = is.read(buffer))!= -) {
raf.write(buffer, , len);
total += len;
//每次讀取流里數(shù)據(jù)之后,把本次讀取的數(shù)據(jù)的長(zhǎng)度顯示至進(jìn)度條
currentProgess += len;
pb.setProgress(currentProgess);
//發(fā)消息,讓主線程刷新文本進(jìn)度
handler.sendEmptyMessage();
//生成臨時(shí)文件保存下載進(jìn)度,用于斷點(diǎn)續(xù)傳,在所有線程現(xiàn)在完畢后刪除臨時(shí)文件
RandomAccessFile progressRaf = new RandomAccessFile(progessFile, "rwd");
progressRaf.write((total+"").getBytes());
progressRaf.close();
}
raf.close();
System.out.println("線程"+threadId+"下載完了");
//當(dāng)所有線程都下在完了之后,刪除臨時(shí)進(jìn)度文件
FinishedThread++;
synchronized (Path) {
if (FinishedThread==ThreadCount) {
for (int i = ; i < ThreadCount; i++) {
File f = new File(Environment.getExternalStorageDirectory(),i+".txt");
f.delete();
}
FinishedThread=;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
以上內(nèi)容是小編跟大家分享的PC版與Android手機(jī)版帶斷點(diǎn)續(xù)傳的多線程下載,希望大家喜歡。
- android實(shí)現(xiàn)多線程下載文件(支持暫停、取消、斷點(diǎn)續(xù)傳)
- Android FTP 多線程斷點(diǎn)續(xù)傳下載\上傳的實(shí)例
- Android多線程+單線程+斷點(diǎn)續(xù)傳+進(jìn)度條顯示下載功能
- Android多線程斷點(diǎn)續(xù)傳下載功能實(shí)現(xiàn)代碼
- Android多線程斷點(diǎn)續(xù)傳下載示例詳解
- Android 使用AsyncTask實(shí)現(xiàn)多任務(wù)多線程斷點(diǎn)續(xù)傳下載
- Android實(shí)現(xiàn)網(wǎng)絡(luò)多線程斷點(diǎn)續(xù)傳下載實(shí)例
- Android編程開(kāi)發(fā)實(shí)現(xiàn)多線程斷點(diǎn)續(xù)傳下載器實(shí)例
- Android 使用AsyncTask實(shí)現(xiàn)多線程斷點(diǎn)續(xù)傳
- android原生實(shí)現(xiàn)多線程斷點(diǎn)續(xù)傳功能
相關(guān)文章
Android RecycleView實(shí)現(xiàn)Item拖拽效果
RecyclerView是Android一個(gè)更強(qiáng)大的控件,其不僅可以實(shí)現(xiàn)和ListView同樣的效果,還有優(yōu)化了ListView中的各種不足。本文將介紹通過(guò)RecyclerView實(shí)現(xiàn)Item拖拽效果以及拖拽位置保存,感興趣的可以參考一下2022-01-01
Android編程開(kāi)發(fā)之ScrollView嵌套GridView的方法
這篇文章主要介紹了Android編程開(kāi)發(fā)之ScrollView嵌套GridView的方法,結(jié)合實(shí)例分析了ScrollView嵌套GridView的相關(guān)注意事項(xiàng)與處理技巧,需要的朋友可以參考下2015-12-12
Flutter Http網(wǎng)絡(luò)請(qǐng)求實(shí)現(xiàn)詳解
這篇文章主要介紹了Flutter Http網(wǎng)絡(luò)請(qǐng)求實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Android ListView優(yōu)化之提高android應(yīng)用效率
android listview優(yōu)化做的好是提高androoid應(yīng)用效率的前提條件,本文給大家介紹Android ListView優(yōu)化之提高android應(yīng)用效率,對(duì)android listview優(yōu)化相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2015-12-12
Android四種數(shù)據(jù)存儲(chǔ)的應(yīng)用方式
這篇文章主要介紹了Android四種數(shù)據(jù)存儲(chǔ)的應(yīng)用方式的相關(guān)資料,希望通過(guò)本文能幫助到大家,讓大家理解掌握Android存儲(chǔ)數(shù)據(jù)的方法,需要的朋友可以參考下2017-10-10
Android registerForActivityResult動(dòng)態(tài)申請(qǐng)權(quán)限案例詳解
這篇文章主要介紹了Android registerForActivityResult動(dòng)態(tài)申請(qǐng)權(quán)限案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
Android開(kāi)發(fā)實(shí)現(xiàn)拍照功能的方法實(shí)例解析
這篇文章主要介紹了Android開(kāi)發(fā)實(shí)現(xiàn)拍照功能的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android拍照功能的具體實(shí)現(xiàn)步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-10-10
Android BottomNavigationView與Fragment重建與重疊問(wèn)題解決方法探索
這篇文章主要介紹了Android BottomNavigationView與Fragment重建與重疊問(wèn)題解決,總的來(lái)說(shuō)這并不是一道難題,那為什么要拿出這道題介紹?拿出這道題真正想要傳達(dá)的是解題的思路,以及不斷優(yōu)化探尋最優(yōu)解的過(guò)程。希望通過(guò)這道題能給你帶來(lái)一種解題優(yōu)化的思路2023-01-01

