Console based progress in Java [duplicate]

2019-01-16 08:28发布

This question already has an answer here:

Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks!

9条回答
对你真心纯属浪费
2楼-- · 2019-01-16 09:02

I have written such a package in Java.

https://github.com/ctongfei/progressbar

查看更多
三岁会撩人
3楼-- · 2019-01-16 09:04
import java.util.Random;

public class ConsoleProgress {

    private static String CURSOR_STRING = "0%.......10%.......20%.......30%.......40%.......50%.......60%.......70%.......80%.......90%.....100%";

    private static final double MAX_STEP = CURSOR_STRING.length() - 1;

    private double max;
    private double step;
    private double cursor;
    private double lastCursor;

    public static void main(String[] args) throws InterruptedException {
        // ---------------------------------------------------------------------------------
        int max = new Random().nextInt(400) + 1;
        // ---------------------------------------------------------------------------------
        // Example of use :
        // ---------------------------------------------------------------------------------
        ConsoleProgress progress = new ConsoleProgress("Progress (" + max + ") : ", max);
        for (int i = 1; i <= max; i++, progress.nextProgress()) {
            Thread.sleep(3L); // a task with no prints
        }
    }

    public ConsoleProgress(String title, int maxCounts) {
        cursor = 0.;
        max = maxCounts;
        step = MAX_STEP / max;
        System.out.print(title);
        printCursor();
        nextProgress();
    }

    public void nextProgress() {
        printCursor();
        cursor += step;
    }

    private void printCursor() {
        int intCursor = (int) Math.round(cursor) + 1;
        System.out.print(CURSOR_STRING.substring((int) lastCursor, intCursor));
        if (lastCursor != intCursor && intCursor == CURSOR_STRING.length())
            System.out.println(); // final print
        lastCursor = intCursor;
    }
}
查看更多
相关推荐>>
4楼-- · 2019-01-16 09:08

I don't think there's a built-in capability to do what you're looking for.

There is a library that will do it (JLine).

See this tutorial

查看更多
登录 后发表回答