How do I create a console progress bar?

The code below demonstrates how to create a progress bar in a console program. The trick is to print the progress status using a System.out.print() and add a carriage return character ("\r") at the end of the string to return the cursor position to the beginning of the line and print the next progress status.

package org.kodejava.example.lang;

public class ConsoleProgressBar {
    public static void main(String[] args) {
        char[] animationChars = new char[]{'|', '/', '-', '\\'};

        for (int i = 0; i <= 100; i++) {
            System.out.print("Processing: " + i + "% " + animationChars[i % 4] + "\r");

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Processing: Done!          ");
    }
}

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply