package Q721;
//断点续传
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Demo03 {
public static void main(String[] args) {
String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int responseCode = conn.getResponseCode();
System.out.println("responseCode = " + responseCode);
//如果响应正确 200
if (responseCode==200){
//下载
InputStream in = conn.getInputStream();
String headerField = conn.getHeaderField("Content-Disposition");
String field = headerField.split(";")[1];
String fileName = field.substring(field.indexOf("\"")+1,field.lastIndexOf("\""));
File file = new File(fileName);
//读一组 写一组
RandomAccessFile raf =new RandomAccessFile(file,"rwd");
int len = 0;
byte[]bytes=new byte[1024];
while ((len = in.read(bytes))!=-1){
raf.write(bytes,0,len);
}
raf.close();
in.close();
System.out.println();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
多线程下载
* 下载文件的一段子线程
* 至少要有三个属性
* url
* stort 文件分段的开始
* end 文件分段的结束
*/
class DownloadThread extends Thread{
private String path;//网速
private long start;//开始的位置
private long end;//结束的位置
/**
* 下载一段
*/
@Override
public void run() {
String path = "http://softforspeed.51xiazai.cn/down/BaiduNetdisk_6.9.7.4.exe";
//三个线程
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("Range","bytes="+start+"-"+end);
int responseCode = conn.getResponseCode();
System.out.println("responseCode = " + responseCode);
//如果响应正确 200
if (responseCode==206){
//下载
int contentLength = conn.getContentLength();
System.out.println("文件总大小 = " + contentLength);
//切割为三分,计算每份的大小
int size = contentLength/3;
/*
假如 contentLength=10 zize = 3
线程1:
线程2:
线程3: size*2-contentLength
*/
for (int i = 0; i < 3; i++) {
DownloadThread dt = new DownloadThread();
dt.setName("线程");
dt.setPath(path);
dt.setStart(i*size);
if (i==2){
dt.setEnd(contentLength);
}else {
dt.setEnd((i*1)*size);
}
dt.start();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getPath() {
return path;
}
public long getStart() {
return start;
}
public long getEnd() {
return end;
}
public void setPath(String path) {
this.path = path;
}
public void setStart(long start) {
this.start = start;
}
public void setEnd(long end) {
this.end = end;
}
}
使用JAVA写一个程序下载网站和软件 单线程和多线程分段下载
最新推荐文章于 2023-06-30 15:02:40 发布