Java 中的命令行进度条

新手上路,请多包涵

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

原文由 g andrieu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 907
2 个回答

我以前实现过这种事情。与其说是 java,不如说是发送到控制台的字符。

关键是 \n\r 之间的区别。 \n 转到新行的开头。但是 \r 只是 回车- 它回到同一行的开头。

所以要做的就是打印你的进度条,例如,打印字符串

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

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

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

你必须记住要做的是完成后,如果你只是打印

"done!\n"

你可能还有一些来自进度条的垃圾就行了。因此,在完成进度条后,请务必打印足够的空白以将其从行中删除。如:

 "done             |\n"

希望有所帮助。

原文由 Matthias Wandel 发布,翻译遵循 CC BY-SA 3.0 许可协议

https://github.com/ctongfei/progressbar , License: MIT

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

推荐使用 Menlo、Fira Mono、Source Code Pro 或 SF Mono 以获得最佳视觉效果。

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

马文

 <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

原文由 koppor 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题