java多线程下载

来源:互联网 发布:udp端口打开 编辑:程序博客网 时间:2024/05/21 10:36
import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class DownLoader {public static void main(String[] args) throws Throwable {new DownLoader().download();}public void download() throws Throwable {String fileName = "F:/qq.exe";String path = "http://dldir1.qq.com/qqfile/qq/QQ8.3/18038/QQ8.3.exe";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int fileLength = conn.getContentLength();// 文件大小长度System.out.println("fileLength = " + fileLength);RandomAccessFile file = new RandomAccessFile(fileName, "rw");file.setLength(fileLength);file.close();conn.disconnect();int threadSize = 3;// 5个线程int threadLength = fileLength % threadSize == 0 ? fileLength/ threadSize : fileLength / threadSize + 1;System.out.println("每条线程下载的长度threadLength = " + threadLength);for (int i = 0; i < threadSize; i++) {int startPosition = i * threadLength;RandomAccessFile threadFile = new RandomAccessFile(fileName, "rw");threadFile.seek(startPosition);new DownLoadThread(i, path, startPosition, threadFile, threadLength).start();}}private class DownLoadThread extends Thread {int threadId;int startPosition;RandomAccessFile threadFile;int threadLength;String path;public DownLoadThread(int threadId, String path, int startPosition,RandomAccessFile threadFile, int threadLength) {this.threadId = threadId;this.path = path;this.startPosition = startPosition;this.threadFile = threadFile;this.threadLength = threadLength;}@Overridepublic void run() {try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");conn.setRequestProperty("Range", "bytes = " + startPosition+ "-");// 指定从文件的什么位置开始下载InputStream inputStream = conn.getInputStream();byte[] buffer = new byte[1024];int len = -1;int length = 0;while (length < threadLength&& (len = inputStream.read(buffer)) != -1) {threadFile.write(buffer, 0, len);length += len;System.out.println((threadId + 1) + "下载进度 = " + length);}threadFile.close();inputStream.close();System.out.println("线程" + (threadId + 1) + "已经下载完成");} catch (Exception e) {e.printStackTrace();System.out.println("线程" + (threadId + 1) + "已经下载出错" + e);}}}}


0 0
原创粉丝点击