首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 控制台百分比進度條:用 \r 回車符實現單行刷新動畫

     編輯:Java 相關知識

無第三方庫、無 ANSI 轉義碼:最樸素的 CLI 進度顯示技巧

控制台輸出預設換行,若想原地更新,核心技巧是 回車符 \r (CR, Carriage Return) 將游標移回行首,配合覆蓋輸出。本範例示範 0%~100% 遞增,每步 Thread.sleep(100),用 \b (Backspace) 逐字符刪除舊數字(教學用),實務上直接 \r 覆蓋整行更簡潔。

原始範例(逐字符刪除)

public static void main(String[] args) throws Exception {
    System.out.print("Progress:");
    for (int i = 1; i <= 100; i++) {
        System.out.print(i + "%");
        Thread.sleep(100);
        // 刪除剛印的數字:長度 = 字符數 + 1(%)
        for (int j = 0; j <= String.valueOf(i).length(); j++) {
            System.out.print("\b"); // 退格
        }
    }
    System.out.println(); // 結束換行
}

改良版:單行覆蓋(推薦)

public static void main(String[] args) throws Exception {
    for (int i = 0; i <= 100; i++) {
        System.out.print("\rProgress: " + i + "%"); // \r 移至行首,覆蓋
        Thread.sleep(50);
    }
    System.out.println(); // 最後換行避免提示符覆蓋
}

進階版:帶進度條視覺化

public static void main(String[] args) throws Exception {
    int width = 50;
    for (int i = 0; i <= 100; i++) {
        int filled = i * width / 100;
        String bar = "[" + "=".repeat(filled) + " ".repeat(width - filled) + "]";
        System.out.print("\r" + bar + " " + i + "%");
        Thread.sleep(30);
    }
    System.out.println();
}
// 輸出:[==========                    ] 22%

注意:String.repeat() 為 Java 11+,舊版用 new String(new char[filled]).replace("\0", "=") 或迴圈拼接。

跨平台兼容性提醒

  • Windows cmd.exe 支援 \r 覆蓋;PowerShell、Linux/macOS 終端機均支援。
  • IDE 控制台(IntelliJ、Eclipse)通常支援,但重導向輸出至檔案時會保留所有中間輸出,建議檢測 System.console() != null 才啟用動畫。
  • 若需顏色、游標控制、多行進度條,請直接使用 JLine 3、Picocli 或 Tqdm4j 等成熟庫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved