import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.NonWritableChannelException;
import java.sql.DatabaseMetaData;
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
/**
* @author lpf
* @version v1.0
* @date 2017年9月7日 模拟迅雷多线程下载
*/
/**
* 任务分配中心
*
* @author SumYu
*
*/
class TaskCenter {
/**
* 同时下载线程数
*/
private int threadCount;
/**
* 下载地址
*/
private String url;
/**
* 本地下载地址
*/
private String localPath = "/Users/SumYu/Desktop/";
/**
* 线程辅助统计
*/
private CountDownLatch latch;
private class DownLoadThread implements Runnable {
private int threadId;
private long startIndex;
private long endIndex;
public DownLoadThread(int threadId, long startIndex, long endIndex) {
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@SuppressWarnings("resource")
@Override
public void run() {
try {
System.out.println("线程"+threadId+"开始下载");
URL downLoadUrl = new URL(url);
HttpURLConnection conn=(HttpURLConnection)downLoadUrl.openConnection();
conn.setRequestMethod("GET");
//向服务器请求下载的部分
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
conn.setConnectTimeout(5000);
int responseCode = conn.getResponseCode();
//服务器返回 code
System.out.println("服务器返回 code"+responseCode);
InputStream inputStream = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(new File(localPath), "rwd");
raf.seek(startIndex);
int len =0;
byte[] buf =new byte[1024];
while ((len=inputStream.read(buf))!=-1) {
raf.write(buf, 0, len);
}
inputStream.close();
raf.close();
latch.countDown();
System.out.println("线程"+threadId+"下载完成");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 多线程下载
*
* @param url
* @param threadNum
*/
public void createNewTask(String url, int threadNum) {
latch=new CountDownLatch(threadNum);
this.url = url;
long taskSize = 0;
try {
URL downloadUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) downloadUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
taskSize = conn.getContentLength();
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("文件总长度" + df.format(taskSize / (1024.00 * 1024.00)) + "MB");
int fileIndex = url.lastIndexOf("/");
String fileName = url.substring(fileIndex+1);
// 分配本地文件夹地址
localPath = localPath +fileName;
RandomAccessFile raf = new RandomAccessFile(new File(localPath), "rwd");
raf.setLength(taskSize);
raf.close();
// 分配任务
long blockSize = taskSize / threadNum;
for (int i = 1; i<= threadNum; i++) {
// 开始的下载的位置
long startIndex = (i - 1) * blockSize;
// 结束的位置
long endIndex = startIndex + i * blockSize - 1;
if (i == threadNum) {
// 最后一将不够分的全部下载完
endIndex = taskSize;
}
System.out.println("线程" + i + "下载" + startIndex + "字节" + endIndex + "字节");
new Thread(new DownLoadThread(i, startIndex, endIndex)).start();
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class HttpDemo {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入下载地址");
String url = scanner.next();
System.out.println("请输入线程数");
int threadNum = scanner.nextInt();
TaskCenter taskCenter = new TaskCenter();
taskCenter.createNewTask(url, threadNum);
new Thread(new GetUrl()).start();
}
}
class GetUrl implements Runnable {
@SuppressWarnings("resource")
@Override
public void run() {
try {
URL url = new URL("http://v3-tt.ixigua.com/a5096beb76cd6b7f41e2a5db57908f57/59b3ac52/video/m/220a2347c0399534ad582a069b1566ab4e3115127c800005bf31d4b0da6/");
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
if (connection.getResponseCode()==200) {
System.out.println(connection.getURL().getFile());
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufIn = new BufferedInputStream(inputStream);
File file = new File("/Users/SumYu/Desktop/test.mp4");
FileOutputStream fileOutputStream = new FileOutputStream(file);
int len;
byte[] buf = new byte[1024];
while ((len=bufIn.read(buf))!=-1) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.flush();
inputStream.close();
fileOutputStream.close();
System.out.println("下载结束");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
java 多线程下载
最新推荐文章于 2021-11-03 20:47:25 发布