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

5

我有一个控制台应用程序,希望在进行一些繁重的计算时,在命令行上放置一个不确定性进度条。目前,我只是像下面的while循环中的每次迭代打印出一个“.”:

while (continueWork){
    doLotsOfWork();
    System.out.print('.');
}

这种方法虽然可行,但如果循环次数较多,会变得有些繁琐。我想知道是否有更好、更聪明的解决方案。


1
总有经典的指数进度条。第一次迭代填充一半,第二次再填充一半(75%),以此类推。或者采用“沙漏”方法,只需一个图标一直旋转即可。除非用户抱怨,否则您当前的解决方案应该可以正常工作。无论如何,进度条的整个目的就是让程序告诉用户“我还没死”。 - Thomas
2
这里有一个或两个... - Will Hartung
4个回答

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) {};
    }
  }
}

3

尝试使用回车符\r


2
在 GUI 应用程序中,通常采用旋转的圆圈或弹跳/循环进度条的方式。我记得许多控制台应用程序使用斜杠、竖线和连字符来创建旋转动画:
\ | / - 

您也可以使用带括号的弹跳字符:
[-----*-----]

当然,如其他答案所提到的,您想使用返回来返回到行的开头,然后打印进度条,覆盖现有的输出。
编辑:威尔在评论中提到了许多更酷的选项: 更酷的 ASCII 等待指示器?

0

如果你知道自己还有多少工作要做和完成了多少,你可以考虑打印出一个百分比完成的条形图形式的进度条。根据这个项目的范围,这可以简单地使用 ascii,或者您也可以考虑使用图形。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接