Java 中基于控制台的进度

2022-09-01 05:40:07

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


答案 1

您可以打印回车符以将光标放回行首。\r

例:

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

    System.out.print("\r[");
    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) {}
  }
}

答案 2

我使用以下代码:

public static void main(String[] args) {
    long total = 235;
    long startTime = System.currentTimeMillis();

    for (int i = 1; i <= total; i = i + 3) {
        try {
            Thread.sleep(50);
            printProgress(startTime, total, i);
        } catch (InterruptedException e) {
        }
    }
}


private static void printProgress(long startTime, long total, long current) {
    long eta = current == 0 ? 0 : 
        (total - current) * (System.currentTimeMillis() - startTime) / current;

    String etaHms = current == 0 ? "N/A" : 
            String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
                    TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
                    TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));

    StringBuilder string = new StringBuilder(140);   
    int percent = (int) (current * 100 / total);
    string
        .append('\r')
        .append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
        .append(String.format(" %d%% [", percent))
        .append(String.join("", Collections.nCopies(percent, "=")))
        .append('>')
        .append(String.join("", Collections.nCopies(100 - percent, " ")))
        .append(']')
        .append(String.join("", Collections.nCopies(current == 0 ? (int) (Math.log10(total)) : (int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
        .append(String.format(" %d/%d, ETA: %s", current, total, etaHms));

    System.out.print(string);
}

结果:enter image description here