天天看點

java多線程下載下傳同一個檔案_使用多線程去下載下傳同一個檔案

1 importjava.io.InputStream;2 importjava.io.RandomAccessFile;3 importjava.net.HttpURLConnection;4 importjava.net.URL;5

6 public classDemo {7 public static String path = "http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe";

8 public static int threadCount = 3;9 public static void main(String[] args) throwsException{10 //1.連接配接伺服器,擷取一個檔案,擷取檔案的長度,在本地建立一個跟伺服器一樣大小的臨時檔案

11 URL url = newURL(path);12 HttpURLConnection conn =(HttpURLConnection)url.openConnection();13 conn.setConnectTimeout(5000);14 conn.setRequestMethod("GET");15 int code =conn.getResponseCode();16 if (code == 200) {17 //伺服器端傳回的資料的長度,實際上就是檔案的長度

18 int length =conn.getContentLength();19 System.out.println("檔案總長度:"+length);20 //在用戶端本地建立出來一個大小跟伺服器端一樣大小的臨時檔案

21 RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");22 //指定建立的這個檔案的長度

23 raf.setLength(length);24 raf.close();25 //假設是3個線程去下載下傳資源。26 //平均每一個線程下載下傳的檔案大小.

27 int blockSize = length /threadCount;28 for (int threadId = 1; threadId <= threadCount; threadId++) {29 //第一個線程下載下傳的開始位置

30 int startIndex = (threadId - 1) *blockSize;31 int endIndex = threadId * blockSize - 1;32 if (threadId == threadCount) {//最後一個線程下載下傳的長度要稍微長一點

33 endIndex =length;34 }35 System.out.println("線程:"+threadId+"下載下傳:---"+startIndex+"--->"+endIndex);36 newDownLoadThread(path, threadId, startIndex, endIndex).start();37 }38

39 }else{40 System.out.printf("伺服器錯誤!");41 }42 }43

44

49 public static class DownLoadThread extendsThread{50 private intthreadId;51 private intstartIndex;52 private intendIndex;53

59 public DownLoadThread(String path, int threadId, int startIndex, intendIndex) {60 super();61 this.threadId =threadId;62 this.startIndex =startIndex;63 this.endIndex =endIndex;64 }65

66 @Override67 public voidrun() {68 try{69 URL url = newURL(path);70 HttpURLConnection conn =(HttpURLConnection)url.openConnection();71 conn.setConnectTimeout(5000);72 conn.setRequestMethod("GET");73 //重要:請求伺服器下載下傳部分檔案 指定檔案的位置

74 conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);75 //從伺服器請求全部資源傳回200 ok如果從伺服器請求部分資源 傳回 206 ok

76 int code =conn.getResponseCode();77 System.out.println("code:"+code);78 InputStream is = conn.getInputStream();//已經設定了請求的位置,傳回的是目前位置對應的檔案的輸入流

79 RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");80 //随機寫檔案的時候從哪個位置開始寫

81 raf.seek(startIndex);//定位檔案

82

83 int len = 0;84 byte[] buffer = new byte[1024];85 while ((len = is.read(buffer)) != -1) {86 raf.write(buffer, 0, len);87 }88 is.close();89 raf.close();90 System.out.println("線程:"+threadId+"下載下傳完畢");91 } catch(Exception e) {92 e.printStackTrace();93 }94 }95

96 }97 }