我有一个控制台应用程序,希望在进行一些繁重的计算时,在命令行上放置一个不确定性进度条。目前,我只是像下面的while循环中的每次迭代打印出一个“.”:
while (continueWork){
doLotsOfWork();
System.out.print('.');
}
这种方法虽然可行,但如果循环次数较多,会变得有些繁琐。我想知道是否有更好、更聪明的解决方案。
我有一个控制台应用程序,希望在进行一些繁重的计算时,在命令行上放置一个不确定性进度条。目前,我只是像下面的while循环中的每次迭代打印出一个“.”:
while (continueWork){
doLotsOfWork();
System.out.print('.');
}
这种方法虽然可行,但如果循环次数较多,会变得有些繁琐。我想知道是否有更好、更聪明的解决方案。
这里有一个例子来展示旋转式进度条和传统样式:
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) {};
}
}
}
尝试使用回车符\r
。
\ | / -
[-----*-----]
如果你知道自己还有多少工作要做和完成了多少,你可以考虑打印出一个百分比完成的条形图形式的进度条。根据这个项目的范围,这可以简单地使用 ascii
,或者您也可以考虑使用图形。