java 断点下载_java的断点下载
public?static?final?int?threadCount?=3;
public?static?void?main(String[]?args)?throws?IOException?{
String?path?=?"http://localhost:8080/oppo.mp4";//下載文件的路徑,也可以是網上的路徑
URL?url?=?new?URL(path);
HttpURLConnection?conn?=?(HttpURLConnection)?url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");//Get請求
int?code?=?conn.getResponseCode();
if(code?==?200){
int?length?=?conn.getContentLength();//文件的大小
RandomAccessFile?raf?=?new?RandomAccessFile("setup.mp4",?"rwd");
/**
"r"?以只讀方式打開。調用結果對象的任何?write?方法都將導致拋出?IOException。
"rw"?打開以便讀取和寫入。如果該文件尚不存在,則嘗試創建該文件。
"rws"?打開以便讀取和寫入,對于?"rw",還要求對文件的內容或元數據的每個更新都同步寫入到底層存儲設備。
"rwd"???打開以便讀取和寫入,對于?"rw",還要求對文件內容的每個更新都同步寫入到底層存儲設備。
*/
raf.setLength(length);//指定創建這個文件的大小
raf.close();//關閉流
//假設是三個線程
int?blockSize?=?length?/?threadCount;
for(int?i?=?1;?i<=threadCount;?i++){
int?startIndex?=?(i-1)*blockSize;
int?endIndex?=?i*blockSize-1;
if(i==threadCount){//當線程為最后一個線程,則末尾等于文件的大小
endIndex?=?length;
}
new?DownloadThread(i,?startIndex,?endIndex,?path).start();//開啟線程
}
}
}
public?static?class?DownloadThread?extends?Thread{
private?int?threadId;//線程的Id
private?int?startIndex;//下載的開始位置
private?int?endIndex;//下載的結束位置
private?String?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()?{
try?{
URL?url?=?new?URL(path);
HttpURLConnection?conn?=?(HttpURLConnection)?url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range",?"bytes="+startIndex+"-"+endIndex);
int?code?=?conn.getResponseCode();
System.out.println("code:"+code);
//從服務器請求全部的資源成功返回?200??如果從服務器請求部分資源成功返回?206
if(code?==?206){
InputStream?is?=?conn.getInputStream();//已經設置了setRequestProperty
//RandomAccessFile隨機文件訪問類,可以指定從某個位置開始下載
RandomAccessFile?raf?=?new?RandomAccessFile("setup.mp4",?"rwd");
raf.seek(startIndex);//定位文件
int?len?=?0;
byte[]?buffer?=?new?byte[1024];
while((len?=?is.read(buffer))?!=?-1){
raf.write(buffer,0,len);
}
is.close();
raf.close();
}
}?catch?(Exception?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}
}
}
總結
以上是生活随笔為你收集整理的java 断点下载_java的断点下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 部落冲突-建筑大师基地军队建筑介绍(兵营
- 下一篇: 微信图片解码