下面的代码是仿照传智播客黎活明老师的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 + " 完毕!");
}
}
}