Java中基于控制台的进度

2022-01-11 00:00:00 console progress-bar refresh java

是否有简单的方法可以在 Java 中实现进程的滚动百分比,以显示在控制台中?我有一个在特定过程中生成的百分比数据类型(双精度),但我可以将它强制到控制台窗口并让它刷新,而不是为每个新的百分比更新打印一个新行吗?我正在考虑推送 cls 和更新,因为我在 Windows 环境中工作,但我希望 Java 具有某种内置功能.欢迎所有建议!谢谢!

Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks!

推荐答案

可以打印回车将光标放回行首.

You can print a carriage return to put the cursor back to the beginning of line.

例子:

public class ProgressDemo {
  static void updateProgress(double progressPercentage) {
    final int width = 50; // progress bar width in chars

    System.out.print("[");
    int i = 0;
    for (; i <= (int)(progressPercentage*width); i++) {
      System.out.print(".");
    }
    for (; i < width; i++) {
      System.out.print(" ");
    }
    System.out.print("]");
  }

  public static void main(String[] args) {
    try {
      for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
        updateProgress(progressPercentage);
        Thread.sleep(20);
      }
    } catch (InterruptedException e) {}
  }
}

相关文章