Last active
July 9, 2022 13:21
-
-
Save madan712/dc1c432362dc466cd80bf02c76a40c88 to your computer and use it in GitHub Desktop.
Java - Progress bar in console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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