5

is it possible to override the last System.out.println output, so i can for example visualize changes in a array or create a progessbar?

For example if i have this class:

class Main{
  public static void main(String[] args){
    for(int i = 0; i < 10; i++){
      for(int j = 0; j < i; j++){
        System.out.print("#");
      }
      System.out.println("");
    }
  }
}

What do i have to do to create this simple progressbar which is shown in a single line and not in 10 seperate lines?

Jeremy S.
  • 6,423
  • 13
  • 48
  • 67
reox
  • 5,036
  • 11
  • 53
  • 98

1 Answers1

4

This works on my particular console (Windows) but it's not terribly portable...

public class Test {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.print("#");
            if (i % 20 == 0) {
                System.out.print("\r                    \r");
            }
            System.out.flush();
            Thread.sleep(100);
        }
    }
}

There's also the Console class, but that doesn't actually buy you very much as far as I can see...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • thanks! it works under linux too, can i also use this to clear multiple lines? – reox Mar 13 '12 at 22:30
  • 1
    @reox: No, it's just using `\r` to go back to the start of the line, then writing a load of spaces, then going back to the start of the line again. You might want to look at [this question](http://stackoverflow.com/questions/439799/whats-a-good-java-curses-like-library-for-terminal-applications) for more elaborate control. – Jon Skeet Mar 13 '12 at 22:34
  • okay, maybe i'll use a jframe with textarea instead :D thank you! – reox Mar 13 '12 at 22:42