java下载远程文件,支持取消 计算进度
时间: 2024-02-06 11:04:02 浏览: 27
你可以使用Java中的URLConnection类或者Apache HttpClient库来下载远程文件。为了支持取消下载,你可以在下载过程中使用多线程或者异步任务,并且在用户请求取消时停止下载线程或者任务。
为了计算下载进度,你可以使用URLConnection类的getContentLength()方法获取文件大小,并且在下载过程中通过已经下载的字节数与文件总大小的比例来计算下载进度,然后通过UI组件显示给用户。
以下是一个简单的使用URLConnection类下载远程文件并且支持取消和计算进度的示例代码:
```java
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class Downloader {
private volatile boolean isCancelled;
private ProgressListener listener;
public Downloader(ProgressListener listener) {
this.listener = listener;
}
public void download(String urlString, String destination) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
int fileSize = connection.getContentLength();
int bytesRead = 0;
byte[] buffer = new byte[1024];
InputStream input = connection.getInputStream();
OutputStream output = new FileOutputStream(destination);
while (!isCancelled) {
int count = input.read(buffer);
if (count == -1) {
break;
}
output.write(buffer, 0, count);
bytesRead += count;
listener.onProgress((double) bytesRead / fileSize);
}
output.close();
input.close();
}
public void cancel() {
isCancelled = true;
}
public interface ProgressListener {
void onProgress(double progress);
}
}
```
你可以通过实现ProgressListener接口来获取下载进度,通过调用Downloader的cancel()方法来取消下载。