Terminal Based Progress Bar for Java Applications
March 31st, 2019 by Micha KopsRecently 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.
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:
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: cli, console, progress-bar, terminal, tools
November 18th, 2020 at 6:47 am
Hi,
Great article.
I’m trying to use ctongfei progress bar (https://github.com/ctongfei/progressbar) to show the progress bar in command line for my file upload utility. I implemented as documented and the progress bar is displayed. However, it puts some more characters ? 33m at the beginning of the progress bar and ? 0m at the end of the progress bar(see image). How can I hide or remove these unnecessary characters?
Display:
Image Upload 100% [33m│████████████████████│[0m 100/100 (0:00:43 / 0:00:00)
My pom.xml:
me.tongfei
progressbar
0.9.0
Code Snippet:
try(ProgressBar pb = new ProgressBar(“Image Upload:”, 100)) {
do {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
TransferProgress progress = upload.getProgress();
long pct = (long) (progress.getPercentTransferred());
pb.stepTo(pct);
} while (upload.isDone() == false);
upload.waitForCompletion();
if(upload.isDone()) {
pb.stepTo(1306);
}
}
Any help is appreciated.