网络_多线程下载

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;
	}
}


你可能感兴趣的:(多线程,android)