核心類別
javax.swing.ProgressMonitorInputStream:包裝 InputStream,自動彈出進度對話框。
javax.swing.ProgressMonitor:可自訂訊息、取消按鈕。
最小可行範例
import javax.swing.*;
import java.io.*;
public class FileProgressDemo {
public static void main(String[] args) throws IOException {
File file = new File("large.dat");
try (ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
null, "讀取中: " + file.getName(), new FileInputStream(file))) {
byte[] buffer = new byte[8192];
int read;
while ((read = pmis.read(buffer)) != -1) {
// 處理資料...
// pmis.getProgressMonitor().setNote("已讀 " + pmis.getProgressMonitor().getProgress() + " bytes");
}
}
}
}
進階:自訂進度更新邏輯
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, "載入...", new FileInputStream(file));
ProgressMonitor monitor = pmis.getProgressMonitor();
monitor.setMillisToDecideToPopup(0); // 立即顯示
monitor.setMillisToPopup(0);
long total = file.length();
long readSoFar = 0;
byte[] buf = new byte[4096];
int n;
while ((n = pmis.read(buf)) != -1) {
readSoFar += n;
int percent = (int) (readSoFar * 100 / total);
monitor.setProgress((int) readSoFar);
monitor.setNote(String.format("已讀 %d%% (%d/%d bytes)", percent, readSoFar, total));
if (monitor.isCanceled()) throw new IOException("使用者取消");
}
關鍵 API
| 方法 | 說明 |
pmis.available() | 剩餘可讀位元組數(部分流不支援) |
pmis.read(buf) | 讀取並自動更新進度 |
monitor.setProgress(n) | 設定目前進度值 |
monitor.setNote(msg) | 設定對話框提示文字 |
monitor.isCanceled() | 檢查使用者是否按取消 |
monitor.close() | 關閉對話框 |
非 Swing 環境替代方案
- Console:
System.out.print("\r進度: " + percent + "%") 配合 \r 回車。
- Log/檔案:定期寫入進度日誌。
- Web:前端輪詢 / WebSocket 推送進度。