java命令行上的非确定性进度条

rgi*_*mmy 5 java console progress-bar

我有一个控制台应用程序,我想在命令行上放置一个非确定性的进度条,同时完成一些繁重的计算.目前我只是打印出'.' 对于while循环中的每次迭代,类似于以下内容:

while (continueWork){
    doLotsOfWork();
    System.out.print('.');
}
Run Code Online (Sandbox Code Playgroud)

哪个有效,但我想知道是否有人有更好/更聪明的想法,因为如果循环中有很多迭代,这可能会有点烦人.

Rea*_*wTo 6

这是一个显示旋转进度条和传统样式的示例:

import java.io.*;
public class ConsoleProgressBar {
    public static void main(String[] argv) throws Exception{
      System.out.println("Rotating progress bar");
      ProgressBarRotating pb1 = new ProgressBarRotating();
      pb1.start();
      int j = 0;
      for (int x =0 ; x < 2000 ; x++){
        // do some activities
        FileWriter fw = new FileWriter("c:/temp/x.out", true);
        fw.write(j++);
        fw.close();
      }
      pb1.showProgress = false;
      System.out.println("\nDone " + j);

      System.out.println("Traditional progress bar");
      ProgressBarTraditional pb2 = new ProgressBarTraditional();
      pb2.start();
      j = 0;
      for (int x =0 ; x < 2000 ; x++){
        // do some activities
        FileWriter fw = new FileWriter("c:/temp/x.out", true);
        fw.write(j++);
        fw.close();
      }
      pb2.showProgress = false;
      System.out.println("\nDone " + j);
    }
}

class ProgressBarRotating extends Thread {
  boolean showProgress = true;
  public void run() {
    String anim= "|/-\\";
    int x = 0;
    while (showProgress) {
      System.out.print("\r Processing " + anim.charAt(x++ % anim.length()));
      try { Thread.sleep(100); }
      catch (Exception e) {};
    }
  }
}

class ProgressBarTraditional extends Thread {
  boolean showProgress = true;
  public void run() {
    String anim  = "=====================";
    int x = 0;
    while (showProgress) {
      System.out.print("\r Processing " 
           + anim.substring(0, x++ % anim.length())
           + " "); 
      try { Thread.sleep(100); }
      catch (Exception e) {};
    }
  }
}
Run Code Online (Sandbox Code Playgroud)