`
HUYIZIZHEN
  • 浏览: 114391 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java实现多线程下载

    博客分类:
  • java
阅读更多
package my;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class MultiThreadDownload {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String path = "http://blog.liuhongwei.cn/wp-content/uploads/2009/08/java-duke-guitar.png";
		try {
			new MultiThreadDownload().downLoad(path, 5);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void downLoad(String path,int threadSize) throws IOException{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(6000);
		//get the length of file
		int fileLength = conn.getContentLength();
		//get the name of file
		String fileName = path.substring(path.lastIndexOf("/"));
		File saveFile = new File(fileName);
		RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
		accessFile.setLength(fileLength);
		accessFile.close();
		int block = (fileLength%threadSize ==0? fileLength/threadSize :(fileLength/threadSize+1));
System.out.println(block);
		for(int threadID=0 ; threadID < threadSize ; threadID++){
			new DownThread(url, saveFile, threadID, block).start();

		}
	}
	
	private final class DownThread extends Thread{
		
		private URL url;
		private File saveFile;
		private int threadID;
		private int block;
		
		public DownThread(URL url, File saveFile, int threadID, int block) {
			this.url = url;
			this.saveFile = saveFile;
			this.threadID = threadID;
			this.block = block;
		}
		
		@Override
		public void run() {
			try {
				//System.out.println("threadID = "+threadID+" 已启动!");
				int startPosition = threadID * block;
				int endPosition = (threadID +1)* block-1;
				
				RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
				accessFile.seek(startPosition);
				
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				
				conn.setRequestMethod("GET");
				conn.setConnectTimeout(6000);
				conn.setRequestProperty("Range", "bytes="+startPosition+"-"+endPosition);
				
				BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
				bis.mark(startPosition);
System.out.println("threadID = "+threadID+" 已启动!"+startPosition);
				byte[] buffer = new byte[1024];
				int len = 0;
				while((len=bis.read(buffer))!=-1){
					accessFile.write(buffer, 0, len);
				}
				bis.close();
				accessFile.close();
//输出信息:
System.out.println("threadID = "+threadID+" 已下载完成!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics