控制台輸出預設換行,若想原地更新,核心技巧是 回車符 \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", "=") 或迴圈拼接。
cmd.exe 支援 \r 覆蓋;PowerShell、Linux/macOS 終端機均支援。System.console() != null 才啟用動畫。