原理
- 不换行,进度更新后,光标跳到行首,覆盖之前的进度条
- 点个赞呗
import java.text.DecimalFormat;
public class ConsoleProgressBarDemo {
private int barLen;
private char showChar;
private DecimalFormat formater = new DecimalFormat("#.##%");
public ConsoleProgressBarDemo(int barLen, char showChar) {
this.barLen = barLen;
this.showChar = showChar;
}
public void show(int value) {
if (value < 0 || value > 100) {
return;
}
reset();
float rate = (float) (value*1.0 / 100);
draw(barLen, rate);
if (value == 100L) {
afterComplete();
}
}
private void draw(int barLen, float rate) {
int len = (int) (rate * barLen);
System.out.print("Progress: ");
for (int i = 0; i < len; i++) {
System.out.print(showChar);
}
for (int i = 0; i < barLen-len; i++) {
System.out.print(" ");
}
System.out.print(" |" + format(rate));
}
private void reset() {
System.out.print('\r');
}
private void afterComplete() {
System.out.print('\n');
}
private String format(float num) {
return formater.format(num);
}
public static void main(String[] args) throws InterruptedException {
ConsoleProgressBarDemo cpb = new ConsoleProgressBarDemo(50, '#');
for (int i = 1; i <= 100; i++) {
cpb.show(i);
Thread.sleep(100);
}
}
}