Progress Bar implementation in Java for Terminal application

Th e”\r” character basically reverts the current cursor back to the 1st column in the current line. This concept should basically work on Mac, Linux and Windows. So to test it I wrote a quick hack and it worked properly:

public class ProgressBar {

    public static void main(String[] args) {
        int size = 10;
        for (int i=1; i<size; i++) {
            try {
                Thread.sleep(500);
                System.out.print("|" + "=".repeat(i) + ">" + " ".repeat(size-i) + "|\r");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.print("|" + "=".repeat(size) + "|\r");
    }
}

// Initial Output
// |=>        |
// Final Output
// |==========|

I got the desired output and a humble do nothing progress bar did come up on terminal. To further this idea I did some internet search and I ended up finding this repo on GitHub. It basically allows you to implement beautiful progress bars for terminal based Java application. The basic concept is the same but it provides much more functionality.

Leave a Reply

Your email address will not be published. Required fields are marked *