Android学习札记(二十)

Android学习笔记(二十)

文件下载

 

DownLoaderTest

package junit.test;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import org.junit.Test;

public class DownLoaderTest {

	@Test
	public void download() throws Exception {
		String urlpath = "http://dl1.g-fox.cn/chinaedition/releases/partners/sites/baidu/FirefoxChinaEdition%202010.10.exe";
		URL url = new URL(urlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setReadTimeout(6 * 1000);
		// 线程数
		int threadsize = 3;
		// 获取文件大小
		int filesize = conn.getContentLength();
		// 每条线程下载的数量
		int block = filesize / 3 + 1;
		conn.disconnect();
		File file = new File("Firefox.exe");
		RandomAccessFile randfile = new RandomAccessFile(file, "rw");
		randfile.setLength(filesize);// 设置文件的大小
		randfile.close();
		for (int i = 0; i < threadsize; i++) {
			int startposition = i * block;// 从网路文件的什么位置开始下载
			RandomAccessFile threadfile = new RandomAccessFile(file, "rw");
			threadfile.seek(startposition);// 从文件的什么位置开始写入
			new DownloadThread(i, url, startposition, threadfile, block)
					.start();
		}
		byte[] quit = new byte[1];
		System.in.read(quit);
		while (!('q' == quit[0])) {
			Thread.sleep(3 * 1000);
		}
	}

	private class DownloadThread extends Thread {
		private int threadid;
		private URL url;
		private int startposition;
		private RandomAccessFile threadfile;
		private int block;

		public DownloadThread(int threadid, URL url, int startposition,
				RandomAccessFile threadfile, int block) {
			this.threadid = threadid;
			this.url = url;
			this.startposition = startposition;
			this.threadfile = threadfile;
			this.block = block;
		}

		@Override
		public void run() {
			try {
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setRequestProperty("Range", "bytes=" + startposition
								+ "-");
				conn.setRequestMethod("GET");
				conn.setReadTimeout(6 * 1000);
				InputStream inputStream = conn.getInputStream();
				byte[] buffer = new byte[1024];
				int len = -1;
				int readfilesize = 0;
				while (readfilesize < block
						&& ((len = inputStream.read(buffer)) != -1)) {
					threadfile.write(buffer, 0, len);
					readfilesize += len;// 累计下载的文件大小
				}
				threadfile.close();
				conn.disconnect();
				System.out.println((this.threadid + 1) + "线程下载完成");
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.run();
		}
	}
}