views:

992

answers:

7

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!

+5  A: 
Progress:

[                         ]
[....................
sangretu
+6  A: 

I don't think there's a built-in capability to do what you're looking for.

There is a library that will do it (JLine).

See this tutorial

Glen
+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
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
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ć
A: 

Clear the console by running the os specific command and then print the new percentage

Thej
+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
I just tried that. It doesn't work. (Tested in Eclipse.)
David Johnstone
@David Johnstone: The example above works at least in traditional console windows.
laalto
@laalto: Yup, tried it in a normal console window and it worked for me.
Michael Angstadt
Beautiful! I'll definitely have to remember this one!
masher
Oh wow, sorry. I tried it in Eclipse also, and just assumed it scrolled down the entire page. Excellent! Thanks!
Monster
ah, sorry. That's pretty neat then :-)
David Johnstone