Skip to content

Instantly share code, notes, and snippets.

@madan712
Last active July 9, 2022 13:21
Show Gist options
  • Save madan712/dc1c432362dc466cd80bf02c76a40c88 to your computer and use it in GitHub Desktop.
Save madan712/dc1c432362dc466cd80bf02c76a40c88 to your computer and use it in GitHub Desktop.
Java - Progress bar in console
public static void showProgressBar(int length, int interval, String message) {
char incomplete = '░';
char complete = '█';
StringBuilder progress = new StringBuilder();
// Initialize
Stream.generate(() -> incomplete).limit(length).forEach(progress::append);
StringBuilder percent = new StringBuilder("0");
String format = "\r[%s] %s%%";
System.out.println(message);
IntStream.range(0, length).forEach(i -> {
progress.replace(i, i + 1, String.valueOf(complete));
percent.delete(0, percent.length()).append(((i + 1) * 100) / length);
System.out.print(String.format(format, progress, percent));
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment