多线程下载文件 java代码示例
时间: 2023-11-04 22:05:52 浏览: 44
以下是一个使用Java多线程下载文件的示例代码:
```java
import java.io.*;
import java.net.URL;
public class MultiThreadedDownloader {
private static final int BUFFER_SIZE = 4096;
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String saveDir = "path/to/save/directory";
int numThreads = 4;
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int fileSize = connection.getContentLength();
// Calculate the file size for each thread
int chunkSize = fileSize / numThreads;
// Create a directory to save the downloaded file
File dir = new File(saveDir);
if (!dir.exists()) {
dir.mkdirs();
}
// Create an array to hold the thread references
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
int startRange = i * chunkSize;
int endRange = (i == numThreads - 1) ? fileSize - 1 : startRange + chunkSize - 1;
String fileName = saveDir + File.separator + "part" + i;
threads[i] = new DownloadThread(fileUrl, fileName, startRange, endRange);
threads[i].start();
}
// Wait for all threads to complete
for (Thread thread : threads) {
thread.join();
}
System.out.println("File downloaded successfully.");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static class DownloadThread extends Thread {
private String fileUrl;
private String fileName;
private int startRange;
private int endRange;
public DownloadThread(String fileUrl, String fileName, int startRange, int endRange) {
this.fileUrl = fileUrl;
this.fileName = fileName;
this.startRange = startRange;
this.endRange = endRange;
}
@Override
public void run() {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range", "bytes=" + startRange + "-" + endRange);
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
请注意,这只是一个简单的示例代码,仅供参考。在实际应用中,您可能还需要添加错误处理、进度跟踪等功能。此外,根据您的需求和具体情况,您可能需要对代码进行自定义修改。