天天看点

java http 断点下载_【java】http断点下载和多线程下载demo

//断点续传和多线程下载

public void httpOnLoad(String fileName,String urlpath) throws Exception

{

URL url = new URL(urlpath);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.setRequestMethod("get");

int threadSize = 3;

int fileLength = conn.getContentLength();

int block = fileLength/3+1;

conn.disconnect();

File file = new File(fileName);

RandomAccessFile randomFile = new RandomAccessFile(file,"RW");

randomFile.setLength(fileLength);

randomFile.close();

for(int i = 0;i<3;i++){

int startPosition = i * block;//从网络文件的什么位置开始下载

RandomAccessFile threadFile = new RandomAccessFile(file,"RW");

threadFile.seek(startPosition);

new DownLoadThread(url,startPosition,threadFile,block).start();

}

}

private class DownLoadThread extends Thread{

URL url;

int startPosition;

RandomAccessFile threadFile;

int block;

public DownLoadThread(URL url,int startPosition,RandomAccessFile threadFile,int block){

this.url = url;

this.startPosition = startPosition;

this.threadFile = threadFile;

this.block = block;

}

@Override

public void run() {

super.run();

HttpURLConnection con;

try {

con = (HttpURLConnection)url.openConnection();

con.setRequestMethod("get");

con.setRequestProperty("Range", "betys"+startPosition+"-");

con.setReadTimeout(6000);

InputStream inputStream = con.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();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}