java多线程下载的实现示例





import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class Main {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		new Main().download("http://gdown.baidu.com/data/wisegame/a3d96bf8e8a5102c/baiduliulanqi_25.apk", 5);
	}
	
	public void download(String downPath, int threadNum) throws Exception{
		URL url = new URL(downPath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		//InputStream in = conn.getInputStream();
		
		if(conn.getResponseCode() == 200){
			int size = conn.getContentLength();
			File file = new File(downPath.substring(downPath.lastIndexOf("/")+1));
			
			//"rwd" 会立刻把数据同步到设备上,防止手机没电数据丢失
			RandomAccessFile raf = new RandomAccessFile(file, "rwd");
			raf.setLength(size); //暂时还没数据
			raf.close();
			
			int block = size%threadNum == 0 ? size/threadNum : size/threadNum + 1;
			for(int i=0; i<threadNum; i++){
				new DownThread(i, block, url, file).start();
			}
			
		}else{
			System.out.println("下载失败");
		}
		
	}
	
	//下载线程类
	private class DownThread extends Thread{
		private int id;
		private int block; //每个线程下载块大小
		private URL url; //地址
		private File file; //下载保存在哪个文件
		
		public DownThread(int i, int block, URL url, File file) {
			this.id = i;
			this.block = block;
			this.url = url;
			this.file = file;
		}
		
		public void run(){
			int start = id * block;
			int end = (id+1) * block - 1;
			
			try {
				RandomAccessFile raf = new RandomAccessFile(file, "rwd");
				raf.seek(start);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestMethod("GET");
				
				//通过头字段,指定获取文件的位置 bytes="1-1000"
				conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
				
				//分段请求文件时,返回码是206
				if(conn.getResponseCode() == 206){
					byte[] buffer = new byte[1024];
					InputStream in = conn.getInputStream();
					int len = 0;
					while( (len=in.read(buffer)) != -1){
						raf.write(buffer, 0, len);
					}
					raf.close();
					in.close();

					System.out.println("线程:" + id + "下载完成");
				}else{
					System.out.println("失败");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("");
		}
		
	}

}





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值