0
点赞
收藏
分享

微信扫一扫

案例 4:Java 多线程实现文件下载器

在网络应用中,文件下载是常见的功能。使用 Java 多线程技术实现文件下载器,可以提高下载速度,充分利用网络带宽。

利用java.net包下的URL和HttpURLConnection类建立网络连接,获取文件输入流。通过多线程将文件分割成多个部分同时下载,每个线程负责下载一部分数据。首先,计算每个线程下载的字节范围:

TypeScript

取消自动换行复制

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

import java.net.HttpURLConnection;

import java.net.URL;

public class FileDownloader implements Runnable {

private String urlStr;

private String filePath;

private long startPos;

private long endPos;

public FileDownloader(String urlStr, String filePath, long startPos, long endPos) {

this.urlStr = urlStr;

this.filePath = filePath;

this.startPos = startPos;

this.endPos = endPos;

}

@Override

public void run() {

try {

URL url = new URL(urlStr);

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

connection.setRequestMethod("GET");

connection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);

connection.setConnectTimeout(5000);

connection.setReadTimeout(5000);

InputStream inputStream = connection.getInputStream();

RandomAccessFile randomAccessFile = new RandomAccessFile(new File(filePath), "rw");

randomAccessFile.seek(startPos);

byte[] buffer = new byte[1024];

int len;

while ((len = inputStream.read(buffer))!= -1) {

randomAccessFile.write(buffer, 0, len);

}

randomAccessFile.close();

inputStream.close();

connection.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

String downloadUrl = "http://example.com/file.zip";

String savePath = "D:/download/file.zip";

int threadCount = 4;

try {

URL url = new URL(downloadUrl);

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

connection.setRequestMethod("GET");

long fileLength = connection.getContentLengthLong();

long partLength = fileLength / threadCount;

Thread[] threads = new Thread[threadCount];

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

long start = i * partLength;

long end = (i == threadCount - 1)? fileLength - 1 : (i + 1) * partLength - 1;

threads[i] = new Thread(new FileDownloader(downloadUrl, savePath, start, end));

threads[i].start();

}

for (Thread thread : threads) {

thread.join();

}

System.out.println("文件下载完成");

} catch (Exception e) {

e.printStackTrace();

}

}

}


该文件下载器通过创建多个线程,分别下载文件的不同部分,最后合并成完整的文件。使用多线程技术能够有效提高下载效率,同时通过设置连接和读取超时,增强了程序的稳定性。

举报

相关推荐

0 条评论