java多线程下载

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

public class DownLoader {

	public static void main(String[] args) throws Throwable {
		new DownLoader().download();
	}

	public void download() throws Throwable {

		String fileName = "F:/qq.exe";

		String path = "http://dldir1.qq.com/qqfile/qq/QQ8.3/18038/QQ8.3.exe";
		URL url = new URL(path);

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setConnectTimeout(5000);

		conn.setRequestMethod("GET");

		int fileLength = conn.getContentLength();// 文件大小长度

		System.out.println("fileLength = " + fileLength);

		RandomAccessFile file = new RandomAccessFile(fileName, "rw");
		file.setLength(fileLength);
		file.close();
		conn.disconnect();

		int threadSize = 3;// 5个线程
		int threadLength = fileLength % threadSize == 0 ? fileLength
				/ threadSize : fileLength / threadSize + 1;
		System.out.println("每条线程下载的长度threadLength = " + threadLength);

		for (int i = 0; i < threadSize; i++) {

			int startPosition = i * threadLength;

			RandomAccessFile threadFile = new RandomAccessFile(fileName, "rw");

			threadFile.seek(startPosition);

			new DownLoadThread(i, path, startPosition, threadFile, threadLength).start();

		}

	}

	private class DownLoadThread extends Thread {

		int threadId;
		int startPosition;
		RandomAccessFile threadFile;
		int threadLength;
		String path;

		public DownLoadThread(int threadId, String path, int startPosition,
				RandomAccessFile threadFile, int threadLength) {

			this.threadId = threadId;
			this.path = path;
			this.startPosition = startPosition;
			this.threadFile = threadFile;
			this.threadLength = threadLength;
		}

		@Override
		public void run() {

			try {

				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();

				conn.setConnectTimeout(5000);
				conn.setRequestMethod("GET");

				conn.setRequestProperty("Range", "bytes = " + startPosition
						+ "-");// 指定从文件的什么位置开始下载

				InputStream inputStream = conn.getInputStream();
				byte[] buffer = new byte[1024];

				int len = -1;
				int length = 0;

				while (length < threadLength
						&& (len = inputStream.read(buffer)) != -1) {
					threadFile.write(buffer, 0, len);
					length += len;

					System.out.println((threadId + 1) + "下载进度 = " + length);
				}

				threadFile.close();
				inputStream.close();
				System.out.println("线程" + (threadId + 1) + "已经下载完成");

			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("线程" + (threadId + 1) + "已经下载出错" + e);

			}

		}

	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值