import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadThread extends Thread {
//资源地址
private String path;
//下载资源文件的哪块区域?
private int index;//当前线程的下标。
private int size;//每个线程要下载的数据个数。
//把特定区域的数据下载下来之后,保存到哪里?
private String save_path;
public DownloadThread(String path, int index, int size, String save_path) {
super();
this.path = path;
this.index = index;
this.size = size;
this.save_path = save_path;
}
@Override
public void run() {
//假设当前是线程3,那么其index是2.
//问当前线程要下载的数据区域是: index*size 到 (index+1)*size-1.
int beginIndex = index*size;
int endIndex = (index+1)*size-1;
try {
//打开连接,获得资源特定位置的数据。
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//关键点:在conn对象中,设置请求的范围。 Range Rover.
//conn.setRequestProperty("Range", "bytes=begin-end");
conn.setRequestProperty("Range", "bytes="+ beginIndex +"-"+endIndex);
//获得相应码,查看是否有获得正确的数据。
if( conn.getResponseCode() == 206 ){
//读取此时下载的特定范围数据。
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024];
int count = 0;
//采用RandomAccessFile将数据保存到本地文件中的特定位置。
RandomAccessFile raf = new RandomAccessFile(save_path, "rw");
//VIP:一定要跳到beginIndex位置,然后再写。
raf.seek(beginIndex);
while( (count=in.read(buffer)) != -1 ){
//将此时有意义的数据写到本地的文件中。
raf.write(buffer,0,count);
}
//关闭资源。
raf.close();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class Demo3 {
public static void main(String[] args) {
/*
*开启多线程,下载zzr.png
* */
/*
* 1,在本地创建一个,和服务器资源文件同样大小的文件。
* */
try {
String path = "http://localhost:8080/TZ_Server/zzr.png";
String save_path = "c:\\ns.png";
//记录线程的个数。
int num = 4;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if( conn.getResponseCode()==200 ){
//获得资源文件的大小。
int fileSize = conn.getContentLength();
RandomAccessFile raf = new RandomAccessFile(save_path, "rw");
//设置本地文件的大小为资源文件的大小。
raf.setLength(fileSize);
raf.close();
/*
*
* 2.开启num个线程下载数据。
*
* */
//获得每个线程要下载的数据个数。
int size = fileSize%num==0?fileSize/num:(fileSize/num+1);
//开启num个线程,开始下载。
for( int index=0;index<=1;index++ ){
new DownloadThread(path, index, size, save_path).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
整理自教程