多线程下载文件雏形_Android学习笔记

下面的代码是仿照传智播客黎活明老师的Android教程后写的,就用多线程下载了一张图片。虽然有点杀鸡用牛刀的意思,但也能说明一些问题。

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

public class DownLoadDemo
{
	public static void main(String[] args) throws Exception
	{
		String path = "http://www.hongname.com/mxtp/z/good/caiyl2/01-1.jpg";

		downLoad(4, path);
	}

	private static String getFileName(String path)
	{
		return path.substring(path.lastIndexOf('/') + 1);
	}

	/**
	 * 下载
	 * 
	 * @param num
	 *            线程总数
	 * @param path
	 *            下载文件的路径
	 * @throws Exception
	 */
	private static void downLoad(int num, String path) throws Exception
	{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		
		conn.setReadTimeout(8000);
		
		int fileLength = conn.getContentLength();// 文件的长度
		File file = new File(getFileName(path));
		
		RandomAccessFile raf = new RandomAccessFile(file, "rwd");
		raf.setLength(fileLength);// 设置文件的大小
		raf.close();// 关闭

		int oneLen = fileLength % num == 0 ? fileLength / num : fileLength
				/ num + 1;// 每个线程需要下载的长度

		for (int i = 0; i < num; i++)
		{
			new DownLoadThread(oneLen, i, path, file).start();// 启动线程
		}
	}

	private static class DownLoadThread extends Thread
	{
		private int id;// 线程ID
		private int length;// 需要下载的长度
		private String path;// 文件路径
		private File file;// 把文件下载到file中

		public DownLoadThread(int length, int id, String path, File file)
		{
			this.length = length;
			this.id = id;
			this.path = path;
			this.file = file;
		}

		@Override
		public void run()
		{
			try
			{
				downLoad();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

		private void downLoad() throws Exception
		{
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setReadTimeout(8000);
			conn.setRequestMethod("GET");
			
			int start = id * length;
			int end = length * (id + 1) - 1;
			conn.setRequestProperty("Range", "bytes=" + start + "-" + end);// HTTP协议中规定好的东西,设置好起始位置和结束位置就OK了
			
			InputStream is = conn.getInputStream();
			RandomAccessFile raf = new RandomAccessFile(file, "rwd");
			
			raf.seek(start);// 跳到该线程负责区域的起始位置
			byte[] b = new byte[1024];
			int len = -1;
			while (-1 != (len = is.read(b)))
			{
				raf.write(b, 0, len);// 往文件里写数据
			}
			System.out.println("线程 " + id + " 完毕!");
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值