我有一个控制台应用程序,当一些繁重的计算完成时,我想在命令行上放置一个不确定的进度条。目前,我只是简单地打印出一个‘’。对于while循环中的每个迭代,如下所示:
while (continueWork){
doLotsOfWork();
System.out.print('.');
}这是可行的,但我想知道是否有人有更好/更聪明的想法,因为如果循环中有很多迭代,这可能会有点恼人。
发布于 2012-02-16 06:54:52
下面是一个显示旋转进度条和传统样式的示例:
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) {};
}
}
}发布于 2012-02-16 06:09:27
尝试使用回车符,\r。
发布于 2012-02-16 06:15:59
在GUI应用程序中,该方法通常是一个旋转的圆圈或弹跳/循环进度条。我记得很多控制台应用程序使用斜杠、竖线和连字符来创建旋转动画:
\ | / - 您还可以在括号中使用跳动字符:
[-----*-----]当然,正如另一个回答中提到的,您希望使用return返回到行的开头,然后打印进度,覆盖现有输出。
编辑: Will在评论中提到的许多更酷的选项:
https://stackoverflow.com/questions/9302117
复制相似问题