JAVA多線程下載

來源:互聯網
上載者:User

標籤:file   nec   public   buffer   orm   tac   form   str   xtend   

package com.jan.test;import java.io.File;import java.io.IOException;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class MultiDownTest {    public static void main(String[] args) throws IOException {        //        String path="http://dldir1.qq.com/qqfile/qq/TIM1.1.5/21175/TIM1.1.5.exe";        //下載線程數量        int threadNums=3;        URL url = new URL(path);        HttpURLConnection con = (HttpURLConnection) url.openConnection();                con.setRequestMethod("GET");        con.setConnectTimeout(5000);        con.setReadTimeout(5000);                if(con.getResponseCode()==200){            int length = con.getContentLength();            int size=length/threadNums;            File file=new File(DownUtil.getFileName(path));            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");            randomAccessFile.setLength(length);            randomAccessFile.close();            for(int i=0;i<threadNums;i++){                int beginindex=i*size;                int endindex=(i+1)*size-1;                //如果為最後一個線程                if(i==threadNums){                    endindex=length-1;                }                System.out.println("線程:"+i+"begin:"+beginindex+" end:"+endindex);                new DownloadThread(beginindex, endindex, i, path,threadNums).start();            }        }        con.disconnect();    }}
package com.jan.test;public class DownUtil {public static String getFileName(String url){return url.substring(url.lastIndexOf("/")+1);}}

  

package com.jan.test;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class DownloadThread extends Thread {private int beginIndex;private int endIndex;private int id;//線程idprivate String path;//private int threadNums;//線程數量private static int hasFinsh;//下載完部分數public DownloadThread(int beginIndex, int endIndex, int id,String path,int threadNums) {super();this.beginIndex = beginIndex;this.endIndex = endIndex;this.id = id;this.path=path;this.threadNums=threadNums;}public void run() {URL url=null;HttpURLConnection con=null;File file = new File(DownUtil.getFileName(path));try {//判斷是否有進度臨時檔案File hasFile=new File(id+".txt");if(hasFile.exists()){BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(hasFile)));beginIndex=Integer.parseInt(reader.readLine());reader.close();}int total=0;url = new URL(path);RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");con= (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");con.setConnectTimeout(5000);con.setReadTimeout(5000);con.setRequestProperty("Range", "bytes="+beginIndex+"-"+endIndex);if(con.getResponseCode()==206){InputStream inputStream = con.getInputStream();randomAccessFile.seek(beginIndex);//建立進度臨時檔案File temp=new File(id+".txt");RandomAccessFile tmpRandomAccessFile = new RandomAccessFile(temp, "rw");byte[] buff=new byte[1024];int len=0;while((len=inputStream.read(buff))!=-1){randomAccessFile.write(buff,0,len);total+=len;tmpRandomAccessFile.seek(0);tmpRandomAccessFile.write(((beginIndex+total)+"").getBytes());System.out.println("線程"+id+" 下載進度:"+(beginIndex+total));}randomAccessFile.close();tmpRandomAccessFile.close();//下載完畢,刪除進度臨時檔案synchronized (path) {hasFinsh+=1;if(hasFinsh==threadNums){for(int i=0;i<threadNums;i++){File f = new File(i+".txt");f.delete();}}}}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{con.disconnect();}}}

  

JAVA多線程下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.