利用Java實(shí)現(xiàn)文件下載進(jìn)度條的方法

小樊
97
2024-10-10 01:50:41

在Java中,可以使用Swing庫(kù)中的JProgressBar組件來(lái)實(shí)現(xiàn)文件下載進(jìn)度條

  1. 首先,確保已經(jīng)導(dǎo)入了以下必要的庫(kù):
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;
  1. 創(chuàng)建一個(gè)JFrame窗口,并在其中添加一個(gè)JProgressBar組件:
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);
    }
}
  1. 創(chuàng)建一個(gè)方法來(lái)下載文件,并在其中更新進(jìn)度條:
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();
    }
}
  1. main方法中調(diào)用downloadFile方法來(lái)下載文件:
public static void main(String[] args) {
    // ... 創(chuàng)建JFrame窗口和JProgressBar組件

    String fileURL = "https://example.com/path/to/your/file.txt";
    String savePath = "D:/downloaded_file.txt";

    downloadFile(fileURL, savePath);
}

現(xiàn)在,當(dāng)你運(yùn)行這個(gè)程序時(shí),它將下載指定的文件,并在JProgressBar組件上顯示下載進(jìn)度。請(qǐng)注意,這個(gè)示例僅適用于HTTP和HTTPS協(xié)議的文件下載。如果你需要下載FTP協(xié)議的文件,你需要使用其他庫(kù)(如Apache Commons Net)來(lái)實(shí)現(xiàn)。

0