网络_多线程下载

int threadCount=3;
String url_st = "http://192.168.11.60:8080/mytry/FilePush?file=122.PNG";
String file_path = "D:/zhang.png";
			//连接网络,获得文件大小。
URL url = new URL(url_st);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setConnectTimeout(10000);
int status = http.getResponseCode();
if(status == 200){
	int len = http.getContentLength();
				//设置存储的位置
	File file = new File(file_path);
	RandomAccessFile raf = new RandomAccessFile(file, "rw");
				//设置缓存文件大小。充大内容。
	raf.setLength(len);
	raf.close();
	int blocksize = len/threadCount;
	for(int i=0;i<threadCount;i++){
					//按照数组的序号
		int start=i*blocksize;
		int end = (i+1)*blocksize-1;
		if(i == (threadCount-1)){
			end = len-1;
		}
		System.out.println("需要下载大小:"+len);
		new Thread(new MyRunnable(url_st,file_path,start,end)).start();
	}
}else{
				//网络错误响应
}


class MyRunnable implements Runnable{
	private String url_st;
	private String file_path;
	private int start;
	private int end;
	public MyRunnable(String url_st, String file_path, int start, int end) {
		this.url_st = url_st;
		this.file_path = file_path;
		this.start = start;
		this.end = end;
		System.out.println(">>>>>>>>>开启一个新的线程。start:"+start+" end:"+end);
	}
	@Override
	public void run() {
		try {
			URL url = new URL(url_st);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Range", "bytes="+start+"-"+end);
			http.setConnectTimeout(10000);
			//开始写
			InputStream is = http.getInputStream();
			RandomAccessFile raf = new RandomAccessFile(file_path,"rwd");
			raf.seek(start);
			byte[] buffer = new byte[1024*10];
			int len =0;
			while((len = is.read(buffer)) != -1){
				raf.write(buffer, 0, len);
				//标记写的位置,可以用来续传
			}
			raf.close();
			http.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}


// 客户端进行 Range 网络请求,或者进行接收的 skip
//输入流的: skip(long bytes);//由于skip不稳定,一般不直接使用
public static void skipFully(InputStream is,long bytes) throws IOException{
	long remaining = bytes;
	long len = 0;
	while(remaining > 0){
		len = is.skip(remaining);
		remaining -= len;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值