本文主要是介绍[Thinking in Java] - No.11 Java控制台进度条,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java实现控制台的进度条,其实就是将之前每一行打印的进度条,反复的打印在同一行上,实现视觉上的进度条增长的效果。
package com.ccd.ym.util;import java.text.DecimalFormat;public class ConsoleProgressBar {private long minimum = 0; // 进度条起始值private long maximum = 100; // 进度条最大值private long barLen = 100; // 进度条长度private char showChar = '='; // 用于进度条显示的字符private DecimalFormat formater = new DecimalFormat("#.##%");/*** 使用系统标准输出,显示字符进度条及其百分比。*/public ConsoleProgressBar() {}/*** 使用系统标准输出,显示字符进度条及其百分比。** @param minimum 进度条起始值* @param maximum 进度条最大值* @param barLen 进度条长度*/public ConsoleProgressBar(long minimum, long maximum,long barLen) {this(minimum, maximum, barLen, '=');}/*** 使用系统标准输出,显示字符进度条及其百分比。** @param minimum 进度条起始值* @param maximum 进度条最大值* @param barLen 进度条长度* @param showChar 用于进度条显示的字符*/public ConsoleProgressBar(long minimum, long maximum,long barLen, char showChar) {this.minimum = minimum;this.maximum = maximum;this.barLen = barLen;this.showChar = showChar;}/*** 显示进度条。** @param value 当前进度。进度必须大于或等于起始点且小于等于结束点(start <= current <= end)。*/public void show(long value) {if (value < minimum || value > maximum) {return;}reset();minimum = value;float rate = (float) (minimum*1.0 / maximum);long len = (long) (rate * barLen);draw(len, rate);if (minimum == maximum) {afterComplete();}}private void draw(long len, float rate) {System.out.print("Progress: ");for (int i = 0; i < len; i++) {System.out.print(showChar);}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 {
// ConsoleProgressBar cpb = new ConsoleProgressBar(0, 100, 30, '#');
// for (int i = 1; i <= 100; i++) {
// cpb.show(i);
// Thread.sleep(100);
// }
// }}
代码很简单,但是存在的问题是,遇到程序打印的log会换行,效果如下:
这篇关于[Thinking in Java] - No.11 Java控制台进度条的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!