多线程下载文件及进度条java代码示例
时间: 2024-02-04 17:04:01 浏览: 26
当然,我可以为您提供一个多线程下载文件及进度条的Java代码示例。下面是一个简单的示例代码:
```java
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadedDownloader {
private static final int BUFFER_SIZE = 4096;
public void downloadFile(String fileUrl, String savePath, int numThreads) throws IOException {
URL url = new URL(fileUrl);
long fileSize = url.openConnection().getContentLengthLong();
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
long chunkSize = fileSize / numThreads;
long startRange = 0;
long endRange = chunkSize;
for (int i = 0; i < numThreads; i++) {
if (i == numThreads - 1) {
endRange = fileSize; // Last thread may download slightly more than others due to rounding error
}
long finalStartRange = startRange;
long finalEndRange = endRange;
executorService.execute(() -> {
try {
downloadChunk(fileUrl, savePath, finalStartRange, finalEndRange);
} catch (IOException e) {
e.printStackTrace();
}
});
startRange += chunkSize;
endRange += chunkSize;
}
executorService.shutdown();
}
private void downloadChunk(String fileUrl, String savePath, long startRange, long endRange) throws IOException {
URL url = new URL(fileUrl);
BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(savePath, true);
byte[] dataBuffer = new byte[BUFFER_SIZE];
int bytesRead;
long downloadedBytes = 0;
while ((bytesRead = in.read(dataBuffer, 0, BUFFER_SIZE)) != -1) {
downloadedBytes += bytesRead;
fileOutputStream.write(dataBuffer, 0, bytesRead);
printProgress(downloadedBytes, startRange, endRange);
}
in.close();
fileOutputStream.close();
}
private void printProgress(long downloadedBytes, long startRange, long endRange) {
float progress = (float) downloadedBytes / (endRange - startRange) * 100;
System.out.printf("Downloaded: %.2f%%\n", progress);
}
public static void main(String[] args) {
MultiThreadedDownloader downloader = new MultiThreadedDownloader();
try {
downloader.downloadFile("http://example.com/file.zip", "save/path/file.zip", 4);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码使用多线程方式下载文件,并在控制台打印下载进度百分比。您可以将`fileUrl`替换为您要下载的文件的URL,`savePath`替换为您要保存文件的路径,`numThreads`替换为您希望使用的线程数。请确保已经引入所需的依赖和相关类。
希望这可以帮助到您!如果您有任何其他问题,请随时提问。