Skip to content

Instantly share code, notes, and snippets.

@barlog-m
Last active December 8, 2015 09:25
Show Gist options
  • Save barlog-m/4bc3d76028197908f4a7 to your computer and use it in GitHub Desktop.
Save barlog-m/4bc3d76028197908f4a7 to your computer and use it in GitHub Desktop.
Java Console Progress Bar
import java.io.IOException;
/**
* Simple console progress bar
*
* Usage:
*
* final int MAX = new Random().nextInt(256);
* System.out.println("MAX: " + MAX);
* ConsoleProgressBar progressBar = new ConsoleProgressBar(MAX);
* for (int i=0; i<=MAX; i++) {
* progressBar.progress(i);
* Thread.sleep(100);
* }
*/
public final class ConsoleProgressBar {
private static final String BEGIN = "\r|";
private static final char END = '|';
private static final char EMPTY = '-';
private static final char FILL = '*';
private static final int OFFSET = BEGIN.length();
private static final int LENGTH = 60;
private final String template = createTemplate();
private final int maxPosition = template.length() - OFFSET;
private final int maxValue;
public ConsoleProgressBar(int maxValue) {
this.maxValue = maxValue;
}
public void progress(int value) {
int position = maxPosition;
position = calculatePosition(value, position);
String s = buildProgressBarString(value, position);
printProgressBar(s);
}
private int calculatePosition(int value, int position) {
if (value < maxValue) {
position = (int) (maxPosition * (value / ((double) maxValue))) + OFFSET;
position = (position > maxPosition) ? maxPosition : position;
}
return position;
}
private String buildProgressBarString(int value, int position) {
StringBuilder sb = new StringBuilder();
sb.append(template.substring(0, position));
int l = maxPosition - position;
if (l > 0) {
sb.append(fill(l));
}
sb.append(END);
sb.append(": ");
sb.append(value);
return sb.toString();
}
private static char[] fill(int length) {
char[] r = new char[length];
for(int i = 0; i < r.length; i++) {
r[i] = EMPTY;
}
return r;
}
private static void printProgressBar(String s) {
try {
System.out.write(s.getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String createTemplate() {
StringBuilder sb = new StringBuilder(BEGIN);
for (int i = 0; i< LENGTH; i++) {
sb.append(FILL);
}
sb.append(END);
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment