java实现多线程下载

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

public class DownLoad {

	private String urlStr;

	public DownLoad(String urlStr) {
		this.urlStr = urlStr;
	}

	/**
	 * 获得下载的资源的名称
	 * 
	 * @return 资源的名称
	 */
	private String getResourceName() {
		return urlStr.substring(urlStr.lastIndexOf("/") + 1);

	}

	/**
	 * 开启四个线程进行下载
	 */
	public void doWork() {
		System.out.println(getResourceName());
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.connect();

			if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

				int size = conn.getContentLength();
				System.out.println(size);
				File file = new File("./" + getResourceName());

				RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
				accessFile.setLength(size);
				accessFile.close();

				int block = (size % 4 == 0) ? (size / 4) : (size / 4 + 1);
				System.out.println(block);
				for (int i = 0; i < 4; i++) {
					new DownLoadThread(url, file, block, i).start();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DownLoad downLoad = new DownLoad(
				"http://downmini.kugou.com/Kugou2012.exe");
		downLoad.doWork();
	}

}

/**
 * 下载线程类
 * @author zimei.zhang
 *
 */
class DownLoadThread extends Thread {
	private URL url; // url地址
	private File file; // 下载文件
	private int block; // 下载信息长度
	private int threadPid; // 线程id

	/**
	 * 构造函数
	 * @param url
	 * @param file
	 * @param block
	 * @param threadPid
	 */
	public DownLoadThread(URL url, File file, int block, int threadPid) {
		this.url = url;
		this.file = file;
		this.block = block;
		this.threadPid = threadPid;
	}

	/**
	 * 实现下载
	 */
	public void run() {
		// 计算该线程要下载信息的范围
		int startPosition = threadPid * block; 
		int endPosition = (threadPid + 1) * block - 1;

		try {
			RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
			accessFile.seek(startPosition);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setReadTimeout(5 * 1000);
			conn.setRequestProperty("Range", "bytes=" + startPosition + "-"
					+ endPosition);
			InputStream in = conn.getInputStream();

			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				accessFile.write(buf, 0, len); 
			}
			in.close();
			accessFile.close();
			System.out.println("Thread id: " + threadPid + " finished");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值