package com.zkq.dowload;
import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class MulThreadDownload {
public static void main(String[] args) throws Exception{
//網絡文件地址
String path="http://192.168.1.186:8080/web/setup_8.8.0.2001b.exe";
new MulThreadDownload().download(path,3);
}
/**
* 下載
* @param path 網絡文件地址
* @param threadsize 線程數
* @throws Exception
*/
private void download(String path,int threadsize) throws Exception {
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode()==200){
int length=conn.getContentLength();//獲取網絡文件的長度
String filename=getFileName(path);
//可以在這裏設置文件的保存路徑 如:"d:/data/"+filename
File file=new File(filename);
RandomAccessFile accessFile=new RandomAccessFile(file, "rwd");
accessFile.setLength(length);
accessFile.close();
//計算每條線程下載的數據量
int block=length%threadsize==0 ? length/threadsize : length/threadsize + 1;
for (int threadid = 0; threadid < threadsize; threadid++) {
//啓動線程
new DownloadThread(threadid,block,url,file).start();
}
}else{
System.out.println("下載失敗");
}
}
/**
* 獲取文件名稱
* @param path
* @return
*/
private String getFileName(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
private class DownloadThread extends Thread{
private int threadid;
private int block;
private URL url;
private File file;
public DownloadThread(int threadid, int block, URL url, File file) {
this.threadid = threadid;
this.block = block;
this.url = url;
this.file = file;
}
public void run() {
int start=threadid * block;//計算該線程從網絡文件 什麼爲是開始下載
int end=(threadid+1) * block - 1;//計算下載到網絡文件的什麼位置結束
try {
RandomAccessFile accessFile=new RandomAccessFile(file, "rwd");
accessFile.seek(start);//設置文件指針的位置
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
if(conn.getResponseCode()==206){
InputStream inStream=conn.getInputStream();
byte[] buffer=new byte[1024];
int len=0;
//文件保存到了項目根目錄
while((len=inStream.read(buffer))!=-1){
accessFile.write(buffer,0,len);
}
accessFile.close();
inStream.close();
}
System.out.println("第"+(threadid+1)+"條線程下載完成");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
java實現多線程下載網絡文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.