import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
new Main().download("http://gdown.baidu.com/data/wisegame/a3d96bf8e8a5102c/baiduliulanqi_25.apk", 5);
}
public void download(String downPath, int threadNum) throws Exception{
URL url = new URL(downPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//InputStream in = conn.getInputStream();
if(conn.getResponseCode() == 200){
int size = conn.getContentLength();
File file = new File(downPath.substring(downPath.lastIndexOf("/")+1));
//"rwd" 会立刻把数据同步到设备上,防止手机没电数据丢失
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.setLength(size); //暂时还没数据
raf.close();
int block = size%threadNum == 0 ? size/threadNum : size/threadNum + 1;
for(int i=0; i<threadNum; i++){
new DownThread(i, block, url, file).start();
}
}else{
System.out.println("下载失败");
}
}
//下载线程类
private class DownThread extends Thread{
private int id;
private int block; //每个线程下载块大小
private URL url; //地址
private File file; //下载保存在哪个文件
public DownThread(int i, int block, URL url, File file) {
this.id = i;
this.block = block;
this.url = url;
this.file = file;
}
public void run(){
int start = id * block;
int end = (id+1) * block - 1;
try {
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(start);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
//通过头字段,指定获取文件的位置 bytes="1-1000"
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
//分段请求文件时,返回码是206
if(conn.getResponseCode() == 206){
byte[] buffer = new byte[1024];
InputStream in = conn.getInputStream();
int len = 0;
while( (len=in.read(buffer)) != -1){
raf.write(buffer, 0, len);
}
raf.close();
in.close();
System.out.println("线程:" + id + "下载完成");
}else{
System.out.println("失败");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("");
}
}
}