Recently I needed to add a progress bar to a Java based terminal/console application and I used a specific library that I’d like to demonstrate in the following snippet.

Terminal based Progress Bar for Java
Figure 1. Terminal based Progress Bar for Java

Dependencies

Using Maven, we just need to add the following dependency:

pom.xml
<dependency>
  <groupId>me.tongfei</groupId>
  <artifactId>progressbar</artifactId>
  <version>0.7.3</version>
</dependency>

Sample Application

The application shows how to set up the progress bar and how to advance its status by-one, by a given amount or to a specific number.

Sample.java
 package com.hascode.tutorial;

import me.tongfei.progressbar.ProgressBar;

public class Sample {

  public static void main(String[] args) throws InterruptedException {
    System.out.println("\n");
    try (ProgressBar pb = new ProgressBar("Downloading the internet", 2000)) {
      pb.step();
      Thread.sleep(1_000);
      pb.step();
      Thread.sleep(1_000);

      pb.stepBy(248); // step by n
      Thread.sleep(1_000);

      pb.stepTo(600); // step directly to n
      Thread.sleep(1_000);

      pb.maxHint(2500);
      pb.stepTo(1337);
      pb.stepTo(2500);
      pb.setExtraMessage("Downloading..."); // Set extra message to display at the end of the bar
    }
    System.out.println("we have downloaded the internet ...");
  }
}

Running the Sample

We may now run the sample application e.g. by using Maven like this:

mvn clean compile exec:java -Dexec.mainClass=com.hascode.tutorial.Sample
[..]
 
Downloading the internet 100% │██████████████████████████████████████████████████████████│ 2500/2500 (0:00:04 / 0:00:00) Downloading...
we have downloaded the internet ...
[..]

Depending on the visual style configured the output might look similar to this one:

Progressbar in action
Figure 2. Progressbar in action

Tutorial Sources

Please feel free to download the tutorial sources from my GitHub repository, fork it there or clone it using Git:

git clone https://github.com/hascode/java-terminal-progressbar-sample.git