- package day04_tomcat;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.RandomAccessFile;
- import java.net.URL;
- import java.net.URLConnection;
- public class Test {
- public static void main(String[] args) throws IOException {
- URL url=new URL("http://127.0.0.1:8080/day05_header/xiao.jpg");
- speedThreadDownload(url, 3,"F:/3.jpg");
- //download(url);
- }
-
- /**
- *
- * @param url 被请求下载的URL
- * @param threadNum 用于下载的线程数
- * @param path 文件保存位置
- * @throws IOException
- */
- private static void speedThreadDownload(URL url,int threadNum,final String path) throws IOException
- {
- int length=url.openConnection().getContentLength();
- System.out.println("文件总字节数:"+length);
-
- final int baseNum=length/threadNum;
- for(int i=1;i<=threadNum;i++){
- final URLConnection con=url.openConnection();
- String by="bytes="+baseNum*(i-1)+"-"+(i==threadNum?length:(baseNum*i-1));
- //System.out.println(by);
- con.setRequestProperty("range", by);
- final int index=baseNum*(i-1);
- new Thread(new Runnable() {
- @Override
- public void run() {
- int len=0;
- byte[] bytes=new byte[1024];
- try (RandomAccessFile daf
- = new RandomAccessFile(path, "rw");
- InputStream in=con.getInputStream();){
- daf.seek(index);
- while((len=in.read(bytes))>0)
- daf.write(bytes,0,len);
-
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
-
- }
复制代码
|
|