在Java中,可以使用Swing库中的JProgressBar组件来实现文件下载进度条
import javax.swing.*;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void main(String[] args) {
JFrame frame = new JFrame("File Downloader");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
frame.getContentPane().add(progressBar, BorderLayout.CENTER);
frame.setVisible(true);
}
}
public static void downloadFile(String fileURL, String savePath) {
try {
URL url = new URL(fileURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int fileSize = connection.getContentLength();
int bytesRead;
byte[] data = new byte[1024];
InputStream inputStream = new BufferedInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
progressBar.setMinimum(0);
progressBar.setMaximum(fileSize);
while ((bytesRead = inputStream.read(data, 0, 1024)) != -1) {
fileOutputStream.write(data, 0, bytesRead);
int progress = (int) (((double) bytesRead / fileSize) * 100);
progressBar.setValue(progress);
}
fileOutputStream.close();
inputStream.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
main
方法中调用downloadFile
方法来下载文件:public static void main(String[] args) {
// ... 创建JFrame窗口和JProgressBar组件
String fileURL = "https://example.com/path/to/your/file.txt";
String savePath = "D:/downloaded_file.txt";
downloadFile(fileURL, savePath);
}
现在,当你运行这个程序时,它将下载指定的文件,并在JProgressBar组件上显示下载进度。请注意,这个示例仅适用于HTTP和HTTPS协议的文件下载。如果你需要下载FTP协议的文件,你需要使用其他库(如Apache Commons Net)来实现。