Using \r (carriage return), we can implement simple command line progress bar. \r goes back to the start of the same line.
ProgressBarDemo.java
import java.util.concurrent.TimeUnit;
public class ProgressBarDemo {
private static final int TOTAL_CHARS = 50;
private static String getChars(int noOfChars, String progressChar) {
StringBuilder builder = new StringBuilder();
builder.append("Installing");
for (int i = 0; i < noOfChars; i++) {
builder.append(progressChar);
}
for (int i = noOfChars; i < TOTAL_CHARS; i++) {
builder.append(" ");
}
return builder.toString();
}
private static void sleep(int noOfMilliSeconds) {
try {
TimeUnit.MILLISECONDS.sleep(noOfMilliSeconds);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void printProgressBar() {
while (true) {
for (int i = 1; i < TOTAL_CHARS; i++) {
System.out.print(getChars(i, "."));
sleep(300);
System.out.print("\r");
}
}
}
public static void main(String[] arg) throws Exception {
printProgressBar();
}
}
Output
You may like
Miscellaneous
No comments:
Post a Comment