码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA多线程下载

时间:2017-06-29 13:32:20      阅读:253      评论:0      收藏:0      [点我收藏+]

标签: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;//线程id
	private 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多线程下载

标签:file   nec   public   buffer   orm   tac   form   str   xtend   

原文地址:http://www.cnblogs.com/wuhua1/p/7093840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!