java多線程斷點下載原理(代碼實例演示)

g3mc 9年前發布 | 60K 次閱讀 多線程 Java開發

      其實多線程斷點下載原理,很簡單的,那么我們就來先了解下,如何實現多線程的斷點下載,首先:你必須明白第一點,那么就是,什么是多線程下載,該知識點可以查看本博客上一篇文章,Android之多線程下載原理,斷點下載呢,其實就是在這個的基礎之上添加了一些東西,那么添加了什么東西了,現在來做一個詳細的了解。

1.在下載的過程中,邊下載,變用一個文件來記錄下載的位置,也就是下載了多少的數據

1.創建文件

2.記錄下載多少數據

3.存儲數據

2.第二次下載的時候,就去讀取文件中是否存有數據,讀取上次下載的位置,作為這次開始下載的位置

1.創建文件對象

2.檢驗是否有次文件和文件里面是否有數據

3.讀取數據,將數據拿給這次的開始位置,也就是從這個數據這里開始下載

3.文件下載完成之后,將記錄的文件刪除,一定要下載完成之后,在將文件刪除,不然會跳出一些異常,比如,這次文件沒了,就要重新開始下載等等

4.以上說了這些是不是稍微明白了些,那么下面來看看真正的實踐吧


示例源碼:

    import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/** 
 * 文件下載器 
 *  
 * @author Administrator zengtao 
 *  
 */  
public class DemoLoader {  
private static DemoLoader loader = new DemoLoader();  
private static int threadCount = 3;  
private static int runningThread = 3;  


private DemoLoader() {  


}  


public static DemoLoader getInstance() {  
return loader;  
}  


/** 
* 去服務器端下載文件 
*  
* @param path 
*            服務器地址 
*/  
public void downFile(String path) {  
// 去服務器端獲取文件的長度,在本地創建一個跟服務器一樣大小的文件  
try {  
URL url = new URL(path);  
HttpURLConnection connection = (HttpURLConnection) url  
.openConnection();  
connection.setDoInput(true);  
connection.setRequestMethod("GET");  
connection.setReadTimeout(5000);  
int code = connection.getResponseCode();  
if (code == 200) {  
// 1.獲取服務器端文件的長度  
int fileLength = connection.getContentLength();  
// 2.本地創建一個跟服務器一樣大小的文件  
RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");  
raf.setLength(fileLength);  
raf.close();  
// 3.假設三個線程下載  
int blockSize = fileLength / threadCount;  
for (int threadId = 0; threadId < threadCount; threadId++) {  
int startIndex = (threadId - 1) * blockSize;  
int endIndex = threadId * blockSize - 1;  
if (threadId == threadCount) {  
endIndex = fileLength;  
}  


// log 假設下載  
System.out.println("假設線程:" + threadId + ",下載:" + startIndex  
+ "--->" + endIndex);  
// 4.開始下載  
new DownLoadThread(threadId, startIndex, endIndex, path)  
.start();  
}  
System.out.println("文件總長度為:" + fileLength);  
} else {  
System.out.println("請求失敗!");  
}  


} catch (Exception e) {  
e.printStackTrace();  
}  
}  


/** 
* 下載文件的線程 
*  
* @author Administrator zengtao 
*  
*/  
public class DownLoadThread extends Thread {  
private int threadId;  
private int startIndex;  
private int endIndex;  
private String path;  


/** 
*  
* @param threadId 
*            線程id 
* @param startIndex 
*            線程下載開始位置 
* @param endIndex 
*            線程下載結束位置 
* @param path 
*            線程下載結束文件放置地址 
*/  
public DownLoadThread(int threadId, int startIndex, int endIndex,  
String path) {  
super();  
this.threadId = threadId;  
this.startIndex = startIndex;  
this.endIndex = endIndex;  
this.path = path;  
}  


@Override  
public void run() {  
super.run();  
try {  
// 1.檢驗是否有存的記錄 -------------------------------------------------------------------------------------------------  
File file = new File(threadId + ".txt");  
if (file.exists() && file.length() > 0) {  
FileInputStream fis = new FileInputStream(file);  
byte[] temp = new byte[1024];  
int leng = fis.read(temp);  
String loadLength = new String(temp, 0, leng);  
int load = Integer.parseInt(loadLength);  
startIndex = load;  
fis.close();  
}  
URL url = new URL(path);  
HttpURLConnection connection = (HttpURLConnection) url  
.openConnection();  
// 2.請求服務器下載部分的文件,制定開始的位置,和結束位置  
connection.setRequestProperty("Range", "bytes=" + startIndex  
+ "-" + endIndex);  
// log 真實下載  
System.out.println("真實線程:" + threadId + ",下載:" + startIndex  
+ "--->" + endIndex);  
connection.setDoInput(true);  
connection.setRequestMethod("GET");  
connection.setReadTimeout(5000);  
// 3.從服務器獲取的全部數據,返回:200,從服務器獲取部分數據,返回:206  
int code = connection.getResponseCode();  
System.out.println("code = " + code);  
InputStream is = connection.getInputStream();  
RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");  
raf.seek(startIndex); // 隨機寫文件的時候,從什么時候開始  
int len = 0;  
int total = 0; // 記錄下載多少  -----------------------------------------  
byte[] buff = new byte[1024];  
while ((len = is.read(buff)) != -1) {  
RandomAccessFile info = new RandomAccessFile(threadId  
+ ".txt", "rwd");  
raf.write(buff, 0, len);  
total += len;  
info.write(("" + startIndex + total).getBytes()); // 4.存數據:(真正下載到開始的位置)下載的+開始的----------------------------------------  
info.close();  
}  
is.close();  
raf.close();  
System.out.println("線程:" + threadId + ",下載完成");  
} catch (Exception e) {  
e.printStackTrace();  
} finally {  
// 5.notice一定要文件都下載完畢之后再將記錄文件刪除  
runningThread--;  
if (runningThread == 0) {  
for (int i = 1; i <= threadCount; i++) {  
File file = new File(i + ".txt");  
file.delete();  
}  
System.out.println("文件下載完畢,刪除記錄文件"); ---------------------------------------------------------------------  
}  
}  
}  
}  
}  </pre><br />
 本文由用戶 g3mc 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!