Skip to content

Instantly share code, notes, and snippets.

@barlog-m
Created December 8, 2015 09:26
Show Gist options
  • Save barlog-m/69c396512cabe91c0ac4 to your computer and use it in GitHub Desktop.
Save barlog-m/69c396512cabe91c0ac4 to your computer and use it in GitHub Desktop.
Simple console unlimited progress bar
import java.io.IOException;
/**
* Simple console unlimited progress bar
*
* Usage:
*
* ConsoleUnlimitedProgressBar progressBar = new ConsoleUnlimitedProgressBar();
* int counter = 0;
* while (true) {
* progressBar.progress(counter++);
* Thread.sleep(100);
* }
*/
public final class ConsoleUnlimitedProgressBar {
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 minPosition = OFFSET;
private int position = minPosition - 1;
private boolean reverse = false;
public void progress(int value) {
processPosition();
String s = buildProgressBarString(value);
printProgressBar(s);
checkDirection();
}
private void processPosition() {
if (!reverse) {
position++;
} else {
position--;
}
}
private void checkDirection() {
if (!reverse) {
if (position >= maxPosition) {
reverse = true;
position = maxPosition;
}
} else {
if (position <= minPosition) {
reverse = false;
position = minPosition;
}
}
}
private String buildProgressBarString(int value) {
StringBuilder sb = new StringBuilder();
sb.append(template.substring(0, position));
sb.append(FILL);
sb.append(template.substring(position + 1, template.length()));
sb.append(": ");
sb.append(value);
return sb.toString();
}
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(EMPTY);
}
sb.append(END);
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment