package com.download;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader {
      
    public void download() throws IOException
    {
        String fileName = "YNote.exe";
        String path = "http://download.ydstatic.com/notewebsite/downloads/YNote.exe";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        int fileLength = conn.getContentLength();
          
        RandomAccessFile file = new RandomAccessFile(fileName,"rw");
        file.setLength(fileLength);
        file.close();
        conn.disconnect();
          
        int threadNum = 10;  //线程数
        //每条线程下载的长度
        int threadLength = fileLength % threadNum == 0 ?
                fileLength/threadNum : fileLength/threadNum + 1;
          
        for(int i=0;i<threadNum;i++)
        {
            int startPosition = i * threadLength;
            //开始写入文件的位置
            RandomAccessFile threadFile = new RandomAccessFile(fileName,"rw");
            threadFile.seek(startPosition);
            new DownloadThread(i, path, startPosition, threadFile, threadLength).start();
        }
                  
    }
      
    class DownloadThread extends Thread
    {
        private int id;
        private int startPosition;
        private RandomAccessFile file;
        private int threadLength;
        private String path;
          
        public DownloadThread(int i,String p,int s,RandomAccessFile f,int l)
        {
            id = i;
            path = p;
            startPosition = s;
            file = f;
            threadLength = l;
        }
          
        @Override
        public void run() {
            super.run();
            try{
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Range", "bytes="+startPosition+"-");
                InputStream is = conn.getInputStream();
                byte[] buffer = new byte[1024*10];
                int len = -1;
                int length = 0;
                while(length<threadLength &&
                        (len=is.read(buffer))!=-1)
                {
                    file.write(buffer,0,len);
                    length += len;
                    System.out.println("Thread"+(id+1)+" 已经下载"+length+"/"+threadLength);
                }
                file.close();
                is.close();
                System.out.println("Thread"+(id+1)+" 已经下载完成");
            }catch(Exception e){
                e.printStackTrace();
                System.out.println("Thread"+(id+1)+" 下载失败");
            }
        }
    }
}