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