Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks!
+2
A:
I'm quite sure there is no way to change anything that the console has already printed because Java considers the console (standard out) to be a PrintStream.
David Johnstone
2009-06-16 12:58:26
A:
Don't know about anything built in to java itself, but you can use terminal control codes to do things like reposition the cursor. Some details here: http://www.termsys.demon.co.uk/vtansi.htm
Tom
2009-06-16 12:58:35
A:
It can be done quite simple. Just use:
System.out.print("*");
instead of
System.out.println("*");
which prints newLine character after every string.
Boris Pavlović
2009-06-16 12:58:39
A:
Clear the console by running the os specific command and then print the new percentage
Thej
2009-06-16 13:02:23
+9
A:
You can print a carriage return \r
to put the cursor back to the beginning of line.
Example:
public class ProgressDemo {
static void updateProgress(double progressPercentage) {
final int width = 50; // progress bar width in chars
System.out.print("\r[");
int i = 0;
for (; i <= (int)(progressPercentage*width); i++) {
System.out.print(".");
}
for (; i < width; i++) {
System.out.print(" ");
}
System.out.print("]");
}
public static void main(String[] args) {
try {
for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
updateProgress(progressPercentage);
Thread.sleep(20);
}
} catch (InterruptedException e) {}
}
}
laalto
2009-06-16 13:03:30
I just tried that. It doesn't work. (Tested in Eclipse.)
David Johnstone
2009-06-16 13:10:34
@David Johnstone: The example above works at least in traditional console windows.
laalto
2009-06-16 13:26:05
@laalto: Yup, tried it in a normal console window and it worked for me.
Michael Angstadt
2009-06-16 19:05:58
Beautiful! I'll definitely have to remember this one!
masher
2009-06-17 04:08:28
Oh wow, sorry. I tried it in Eclipse also, and just assumed it scrolled down the entire page. Excellent! Thanks!
Monster
2009-06-18 14:28:50
ah, sorry. That's pretty neat then :-)
David Johnstone
2009-06-19 00:12:21