Terminal Based Progress Bar for Java Applications

March 31st, 2019 by

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

Terminal based Progress Bar for Java

 

Dependencies

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

<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.

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

Progressbar in action

Tutorial Sources

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

git clone https://bitbucket.org/hascode/java-terminal-progressbar-sample.git

Resources

Tags: , , , ,

Leave a Reply

Please note, that no personal information like your IP address is stored and you're not required to enter you real name.

Comments must be approved before they are published, so please be patient after having posted a comment - it might take a short while.

Please leave these two fields as-is:
Search
Categories