Java控制台进度条,批处理数据必备!

需求描述

写了好多批量处理数据的代码了,但是从一开始连日志都不知道打印,只知道干等着,到后来慢慢关注日志和性能。发现通过一条一条的日志来查看进度真是一个费力不讨好的事情。最近才想到用进度条来展示程序的进度,真是兜了一个大圈子😂,希望看到之后有收获的同学能顺手点个赞,谢谢!


import java.util.Arrays;

public class ConsoleProgressBar {

    public static void printBar(int total, int now) {
        // 参数校验
        check(total, now);
        // 计算百分比
        double percent = (double) now / total * 100;
        // 计算格数,默认100格
        int fillNum = (int) percent;
        // 生成进度条
        String bar = generateBar(fillNum);
        // 输出
        System.out.printf("\rProgress [%s] %.2f%%", bar, percent);
        if (fillNum == 100) System.out.print('\n');
    }

    public static void printBar(int total, int now, String elapse) {
        // 参数校验
        check(total, now);
        // 计算
        double percent = (double) now / total * 100;
        // 计算格数,默认100格
        int fillNum = (int) percent;
        // 生成进度条
        String bar = generateBar(fillNum);
        // 输出
        System.out.printf("\rProgress [%s] %.2f%% | elapse: %s", bar, percent, elapse);
        if (fillNum == 100) System.out.print('\n');
    }

    public static String generateBar(int total, int fillNum, char c) {
        char[] chars = new char[total];
        Arrays.fill(chars, 0, fillNum, c);
        Arrays.fill(chars, fillNum, total, ' ');
        return String.valueOf(chars);
    }

    private static String generateBar(int fillNum) {
        return generateBar(100, fillNum, '#');
    }

    private static void check(int total, int now) {
        if (total < now) throw new IllegalArgumentException("total can't smaller than now");
        if (total < 1) throw new IllegalArgumentException("total can't smaller than 1");
        if (now < 0) throw new IllegalArgumentException("now can't smaller than 0");
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值