在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)來實現。