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.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(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

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

1 Comments

  1. I have recently faced the same problem, you can check my code:
    I have set it for one # on 5%, which you can modify later.

    public static void main (String[] args) throws java.lang.Exception {
        int i = 0;
        while(i < 21) {
            System.out.print("[");
            for (int j=0;j<i;j++) {
                System.out.print("#");
            }
    
            for (int j=0;j<20-i;j++) {
                System.out.print(" ");
            }
    
            System.out.print("] "+  i*5 + "%");
            if(i<20) {
                System.out.print("\r");
                Thread.sleep(300);
            }
            i++;
        }
        System.out.println();
    }
    
    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.