简单的多线程多点下载
一直奇怪IDM的下载为啥那么牛逼,最近正好复习下载就记录下。
首先你要了解多线程下载就得明白一个牛逼的IO流RandomAccessFile
1 RandomAccessFile
主要功能是完成随机读取功能,可以读取指定位置的内容
1.1 Api:
- close()//关闭操作
- read(byte[] b)//将内容读取到一个byte数组之中
- readByte()//读取一个字节
- readInt()//从文件中读取整型数据
- seek(long pos)//设置读指针的位置
- writeBytes(String s)//将一个字符串写入到文件之中,按字节的方式处理。
- writeInt(int v)//将一个int型数据写入文件,长度为4位
- skipBytes(int n)//指针跳过多少个字节
实例化此类的时候需要传递File类,告诉程序应该操作的是哪个文件,之后有一个模式,文件的打开模式
1.2 文本模式:
- r:读模式
- w:只写
- rw:读写,如果使用此模式,如果此文件不存在,则会自动创建。
创建事例写入操作:
public class RandomAccessFileDemo01{
// 所有的异常直接抛出,程序中不再进行处理
public static void main(String args[]) throws Exception{
File f = new File("d:" + File.separator + "test.txt") ; // 指定要操作的文件
RandomAccessFile rdf = null ; // 声明RandomAccessFile类的对象
rdf = new RandomAccessFile(f,"rw") ;// 读写模式,如果文件不存在,会自动创建
String name = null ;
int age = 0 ;
name = "zhangsan" ; // 字符串长度为8
age = 30 ; // 数字的长度为4
rdf.writeBytes(name) ; // 将姓名写入文件之中
rdf.writeInt(age) ; // 将年龄写入文件之中
name = "lisi " ; // 字符串长度为8
age = 31 ; // 数字的长度为4
rdf.writeBytes(name) ; // 将姓名写入文件之中
rdf.writeInt(age) ; // 将年龄写入文件之中
name = "wangwu " ; // 字符串长度为8
age = 32 ; // 数字的长度为4
rdf.writeBytes(name) ; // 将姓名写入文件之中
rdf.writeInt(age) ; // 将年龄写入文件之中
rdf.close() ; // 关闭
}
}; // 关闭
以上完成了写入的操作,每条数据的长度都是12位
1.3写入操作
写完之后,开始读取数据。写的时候可以将一个字符串写入,读的时候需要一个个的以字节的形式读取出来
public class RandomAccessFileDemo02{
// 所有的异常直接抛出,程序中不再进行处理
public static void main(String args[]) throws Exception{
File f = new File("d:" + File.separator + "test.txt") ; // 指定要操作的文件
RandomAccessFile rdf = null ; // 声明RandomAccessFile类的对象
rdf = new RandomAccessFile(f,"r") ;// 以只读的方式打开文件
String name = null ;
int age = 0 ;
byte b[] = new byte[8] ; // 开辟byte数组
// 读取第二个人的信息,意味着要空出第一个人的信息
rdf.skipBytes(12) ; // 跳过第一个人的信息
for(int i=0;i<b.length;i++){
b[i] = rdf.readByte() ; // 读取一个字节
}
name = new String(b) ; // 将读取出来的byte数组变为字符串
age = rdf.readInt() ; // 读取数字
System.out.println("第二个人的信息 --> 姓名:" + name + ";年龄:" + age) ;
// 读取第一个人的信息
rdf.seek(0) ; // 指针回到文件的开头
for(int i=0;i<b.length;i++){
b[i] = rdf.readByte() ; // 读取一个字节
}
name = new String(b) ; // 将读取出来的byte数组变为字符串
age = rdf.readInt() ; // 读取数字
System.out.println("第一个人的信息 --> 姓名:" + name + ";年龄:" + age) ;
rdf.skipBytes(12) ; // 空出第二个人的信息
for(int i=0;i<b.length;i++){
b[i] = rdf.readByte() ; // 读取一个字节
}
name = new String(b) ; // 将读取出来的byte数组变为字符串
age = rdf.readInt() ; // 读取数字
System.out.println("第三个人的信息 --> 姓名:" + name + ";年龄:" + age) ;
rdf.close() ; // 关闭
}
};
输出:
第二个人的信息 --> 姓名:lisi ;年龄:31
第一个人的信息 --> 姓名:zhangsan;年龄:30
第三个人的信息 --> 姓名:wangwu ;年龄:32
2.多线程下载
我们就用所学之前的知识,猜想一下怎么去做?
- 请求url地址获取服务端资源的大小
- 建立本地的文件相同大小的一个文件(占位)
- 分配每个线程下载文件的开始位置和结束位置
- 开启线程进行下载
2.1 请求url地址获取服务端资源的大小
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10 * 1000);
int code = openConnection.getResponseCode();
if (code == 200) {
// 获取资源的大小
int filelength = openConnection.getContentLength();
}
2.2 建立本地的文件相同大小的一个文件(占位)
RandomAccessFile randomAccessFile = new RandomAccessFile(
new File(getFileName(path)), "rw");
randomAccessFile.setLength(filelength);// 设置随机访问文件的大小,本地的占位文件
randomAccessFile.close();
2.3 分配每个线程下载文件的开始位置和结束位置
blockSize = filelength / threadCount;// 计算出每个线程理论下载大小
for (int threadId = 0; threadId < threadCount; threadId++) {
int startIndex = threadId * blockSize;// 计算每个线程下载的开始位置
int endIndex = (threadId + 1) * blockSize - 1;// 计算每个线程下载的结束位置
// 如果是最后一个线程,结束位置需要单独计算
if (threadId == threadCount - 1) {
endIndex = filelength - 1;
}
//开启线程去执行下载
new DownloadThread(threadId, startIndex, endIndex).start();
....
}
2.4 开启线程进行下载
- 分段请求网络连接,分段保存文件到本地
- 这里就要做判断了,如果文件已经存在,就要读取文件获取上次下载的位置,下载剩下的数据
- 如果不存在就从开始位置进行下载
- 下载完后就使用RandomAccessFile 进行汇总
2.4.1 分段请求网络连接,分段保存文件到本地
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10 * 1000);
System.out.println("理论上下载: 线程:" + threadId + ",开始位置:"
+ startIndex + ";结束位置:" + endIndex);
File file2 = new File(threadId + ".txt");
2.4.2 如果文件已经存在,就要读取文件获取上次下载的位置,下载剩下的数据
if (file2.exists()) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(file2)));
String lastPostion_str = bufferedReader.readLine();
lastPostion = Integer.parseInt(lastPostion_str);// 读取文件获取上次下载的位置
// 设置分段下载的头信息。 Range:做分段数据请求用的。
openConnection.setRequestProperty("Range", "bytes:"
+ lastPostion + "-" + endIndex);// bytes:0-500:请求服务器资源中0-500之间的字节信息
// 501-1000:
System.out.println("实际下载: 线程:" + threadId + ",开始位置:"
+ lastPostion + ";结束位置:" + endIndex);
bufferedReader.close();
}
2.4.3 如果不存在就从开始位置进行下载
else {
lastPostion = startIndex;
// 设置分段下载的头信息。 Range:做分段数据请求用的。
openConnection.setRequestProperty("Range", "bytes:"
+ lastPostion + "-" + endIndex);// bytes:0-500:请求服务器资源中0-500之间的字节信息
// 501-1000:
System.out.println("实际下载: 线程:" + threadId + ",开始位置:"
+ lastPostion + ";结束位置:" + endIndex);
}
2.4.4 下载完后就使用RandomAccessFile 进行汇总
if (openConnection.getResponseCode() == 206) {// 200:请求全部资源成功,
// 206代表部分资源请求成功
InputStream inputStream = openConnection.getInputStream();
// 请求成功将流写入本地文件中,已经创建的占位那个文件中
RandomAccessFile randomAccessFile = new RandomAccessFile(
new File(getFileName(path)), "rw");
randomAccessFile.seek(lastPostion);// 设置随机文件从哪个位置开始写。
// 将流中的数据写入文件
byte[] buffer = new byte[1024];
int length = -1;
int total = 0;// 记录本次线程下载的总大小
while ((length = inputStream.read(buffer)) != -1) {
randomAccessFile.write(buffer, 0, length);
total = total + length;
// 去保存当前线程下载的位置,保存到文件中
int currentThreadPostion = lastPostion + total;// 计算出当前线程本次下载的位置
// 创建随机文件保存当前线程下载的位置
File file = new File(threadId + ".txt");
RandomAccessFile accessfile = new RandomAccessFile(
file, "rwd");
accessfile.write(String.valueOf(currentThreadPostion)
.getBytes());
accessfile.close();
}
3.全部代码
public class MuchThreadDown {
private static int threadCount = 3;// 开启3个线程
private static int blockSize = 0;// 每个线程下载的大小
private static int runningTrheadCount = 0;// 当前运行的线程数
private static String path = "http://192.168.13.83:8080/itheima74/feiq.exe";
/**
* @param args
*/
public static void main(String[] args) {
try {
// 1.请求url地址获取服务端资源的大小
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10 * 1000);
int code = openConnection.getResponseCode();
if (code == 200) {
// 获取资源的大小
int filelength = openConnection.getContentLength();
// 2.在本地创建一个与服务端资源同样大小的一个文件(占位)
RandomAccessFile randomAccessFile = new RandomAccessFile(
new File(getFileName(path)), "rw");
randomAccessFile.setLength(filelength);// 设置随机访问文件的大小,本地的占位文件
randomAccessFile.close();
// 3.要分配每个线程下载文件的开始位置和结束位置。
blockSize = filelength / threadCount;// 计算出每个线程理论下载大小
for (int threadId = 0; threadId < threadCount; threadId++) {
int startIndex = threadId * blockSize;// 计算每个线程下载的开始位置
int endIndex = (threadId + 1) * blockSize - 1;// 计算每个线程下载的结束位置
// 如果是最后一个线程,结束位置需要单独计算
if (threadId == threadCount - 1) {
endIndex = filelength - 1;
}
// 4.开启线程去执行下载
new DownloadThread(threadId, startIndex, endIndex).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class DownloadThread extends Thread {
private int threadId;
private int startIndex;
private int endIndex;
private int lastPostion;
public DownloadThread(int threadId, int startIndex, int endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
synchronized (DownloadThread.class) {
runningTrheadCount = runningTrheadCount + 1;// 开启一线程,线程数加1
}
// 分段请求网络连接,分段保存文件到本地
try {
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setRequestMethod("GET");
openConnection.setConnectTimeout(10 * 1000);
System.out.println("理论上下载: 线程:" + threadId + ",开始位置:"
+ startIndex + ";结束位置:" + endIndex);
// 读取上次下载结束的位置,本次从这个位置开始直接下载。
File file2 = new File(threadId + ".txt");
if (file2.exists()) {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(file2)));
String lastPostion_str = bufferedReader.readLine();
lastPostion = Integer.parseInt(lastPostion_str);// 读取文件获取上次下载的位置
// 设置分段下载的头信息。 Range:做分段数据请求用的。
openConnection.setRequestProperty("Range", "bytes:"
+ lastPostion + "-" + endIndex);// bytes:0-500:请求服务器资源中0-500之间的字节信息
// 501-1000:
System.out.println("实际下载: 线程:" + threadId + ",开始位置:"
+ lastPostion + ";结束位置:" + endIndex);
bufferedReader.close();
} else {
lastPostion = startIndex;
// 设置分段下载的头信息。 Range:做分段数据请求用的。
openConnection.setRequestProperty("Range", "bytes:"
+ lastPostion + "-" + endIndex);// bytes:0-500:请求服务器资源中0-500之间的字节信息
// 501-1000:
System.out.println("实际下载: 线程:" + threadId + ",开始位置:"
+ lastPostion + ";结束位置:" + endIndex);
}
if (openConnection.getResponseCode() == 206) {// 200:请求全部资源成功,
// 206代表部分资源请求成功
InputStream inputStream = openConnection.getInputStream();
// 请求成功将流写入本地文件中,已经创建的占位那个文件中
RandomAccessFile randomAccessFile = new RandomAccessFile(
new File(getFileName(path)), "rw");
randomAccessFile.seek(lastPostion);// 设置随机文件从哪个位置开始写。
// 将流中的数据写入文件
byte[] buffer = new byte[1024];
int length = -1;
int total = 0;// 记录本次线程下载的总大小
while ((length = inputStream.read(buffer)) != -1) {
randomAccessFile.write(buffer, 0, length);
total = total + length;
// 去保存当前线程下载的位置,保存到文件中
int currentThreadPostion = lastPostion + total;// 计算出当前线程本次下载的位置
// 创建随机文件保存当前线程下载的位置
File file = new File(threadId + ".txt");
RandomAccessFile accessfile = new RandomAccessFile(
file, "rwd");
accessfile.write(String.valueOf(currentThreadPostion)
.getBytes());
accessfile.close();
}
// 关闭相关的流信息
inputStream.close();
randomAccessFile.close();
System.out.println("线程:" + threadId + ",下载完毕");
// 当所有线程下载结束,删除存放下载位置的文件。
synchronized (DownloadThread.class) {
runningTrheadCount = runningTrheadCount - 1;// 标志着一个线程下载结束。
if (runningTrheadCount == 0) {
System.out.println("所有线程下载完成");
for (int i = 0; i < threadCount; i++) {
File file = new File(i + ".txt");
System.out.println(file.getAbsolutePath());
file.delete();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.run();
}
}
public static String getFileName(String url) {
return url.substring(url.lastIndexOf("/"));
}
}