자바 다 중 스 레 드 다운로드 구현 예제

2602 단어
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("");
		}
		
	}

}

좋은 웹페이지 즐겨찾기