问题

我有一个在命令行模式下运行的Java程序。我想显示一个进度条,显示完成工作的百分比。你会在unix下使用wget看到同样的进度条。这可能吗?


#1 热门回答(143 赞)

我以前实现过这种事情。它不是关于java,而是发送到控制台的字符。

关键是\n\r.\n之间的区别是新线的开始。但\r只是回归 - 它回到了同一行的开头。

因此,要做的是打印进度条,例如,通过打印字符串

"|========        |\r"

在进度条的下一个刻度线上,用较长的条覆盖同一行。 (因为我们正在使用\ r,我们保持在同一条线上)例如:

"|=========       |\r"

你必须要记住的是,如果你刚刚打印,那就完成了

"done!\n"

你可能仍然从该行的进度条中有一些垃圾。因此,在完成进度条之后,请务必打印足够的空格以将其从行中删除。如:

"done             |\n"

希望有所帮助。


#2 热门回答(20 赞)

我发现以下代码可以正常工作。它将字节写入输出缓冲区。也许使用像System.out.println()方法这样的编写器的方法会替换\r\n的出现,以匹配目标的本机行结尾(如果配置不正确)。

public class Main{
    public static void main(String[] arg) throws Exception {
        String anim= "|/-\\";
        for (int x =0 ; x < 100 ; x++) {
            String data = "\r" + anim.charAt(x % anim.length()) + " " + x;
            System.out.write(data.getBytes());
            Thread.sleep(100);
        }
    }
}

#3 热门回答(12 赞)

https://github.com/ctongfei/progressbar,许可证:麻省理工学院

简单的控制台进度条。进度条写入现在在另一个线程上运行。

图片描述

建议使用Menlo,Fira Mono,Source Code Pro或SF Mono以获得最佳视觉效果。

对于Consolas或Andale Mono字体,请使用ProgressBarStyle.ASCII(见下文),因为这些字体中的框图字形未正确对齐。

图片描述

Maven的:

<dependency>
  <groupId>me.tongfei</groupId>
  <artifactId>progressbar</artifactId>
  <version>0.5.5</version>
</dependency>

用法:

ProgressBar pb = new ProgressBar("Test", 100); // name, initial max
 // Use ProgressBar("Test", 100, ProgressBarStyle.ASCII) if you want ASCII output style
pb.start(); // the progress bar starts timing
// Or you could combine these two lines like this:
//   ProgressBar pb = new ProgressBar("Test", 100).start();
some loop {
  ...
  pb.step(); // step by 1
  pb.stepBy(n); // step by n
  ...
  pb.stepTo(n); // step directly to n
  ...
  pb.maxHint(n);
  // reset the max of this progress bar as n. This may be useful when the program
  // gets new information about the current progress.
  // Can set n to be less than zero: this means that this progress bar would become
  // indefinite: the max would be unknown.
  ...
  pb.setExtraMessage("Reading..."); // Set extra message to display at the end of the bar
}
pb.stop() // stops the progress bar

原文链接