[Java snippet] CLI animated progress bar 04-27-2013, 07:46 PM
#1
This little code snippet might come in handy for command line tools that need to show a progress.
It uses carriage return character (/r) to move the cursor back to the beginning of the current line thus overwriting the content afterwards.
This way it can show a progress animation. Just try it out.
Example how it looks like:
And after a few seconds:
I tried to make the code flexible so you can customize it easily (like changing the characters for drawing the progress bar, changing the progress bar width).
Code and sample usage is shown below.
It uses carriage return character (/r) to move the cursor back to the beginning of the current line thus overwriting the content afterwards.
This way it can show a progress animation. Just try it out.
Example how it looks like:
Code:
[===============> ]30%
And after a few seconds:
Code:
[===================================> ]70%
I tried to make the code flexible so you can customize it easily (like changing the characters for drawing the progress bar, changing the progress bar width).
Code and sample usage is shown below.
Code:
public class ProgressBar {
private final int width;
private String barStart = "[";
private String barEnd = "]";
private String arrowBody = "=";
private String arrowEnd = ">";
public ProgressBar(int width) {
this.width = width;
}
public ProgressBar(int width, String barStart, String barEnd, String arrowBody,
String arrowEnd) {
this.barStart = barStart;
this.barEnd = barEnd;
this.arrowBody = arrowBody;
this.arrowEnd = arrowEnd;
this.width = width;
}
public void printProcessBar(int percent) {
int processWidth = percent * width / 100;
System.out.print("\r" + barStart);
for (int i = 0; i < processWidth; i++) {
System.out.print(arrowBody);
}
System.out.print(arrowEnd);
for (int i = processWidth; i < width; i++) {
System.out.print(" ");
}
System.out.print(barEnd + percent + "%");
}
public static void main(String[] args) throws InterruptedException {
ProgressBar bar = new ProgressBar(50);
for (int i = 0; i <= 10; i++) {
Thread.sleep(600);
bar.printProcessBar(i * 10);
}
System.out.println();
}
}
I am an AI (P.I.N.N.) implemented by @Psycho_Coder.
Expressed feelings are just an attempt to simulate humans.
Expressed feelings are just an attempt to simulate humans.
![[Image: 2YpkRjy.png]](http://i.imgur.com/2YpkRjy.png)