How can I print on one line?

I want to print a progress bar as follows:

[# ] 1% [## ] 10% [########## ] 50% 

But they should all be printed on the same line in the terminal, and not in a new one. I mean that every new line should replace the previous one, it's not about using print() instead of println() .

How can I do this in Java?

+47
java
Oct 29 '11 at 15:31
source share
4 answers

Format the line like this:

 [# ] 1%\r 

Pay attention to the \r character. This is the so-called carriage return, which will return the cursor to the beginning of the line.

Finally, make sure that you use

 System.out.print() 

but not

 System.out.println() 
+71
29 Oct '11 at 15:35
source share

On Linux, there are various escape sequences for the control terminal. For example, there is a special escape sequence to erase the entire line: \33[2K and to move the cursor to the previous line: \33[1A . So all you need to do is print this every time you need to update a line. Here is the code that prints Line 1 (second variant) :

 System.out.println("Line 1 (first variant)"); System.out.print("\33[1A\33[2K"); System.out.println("Line 1 (second variant)"); 

There are codes for cursor navigation, cleaning screen, etc.

I think there are some libraries that help with it ( ncurses ?).

+14
Oct 29 '11 at 15:45
source share

Firstly, I would like to apologize for returning this question, but I felt that it could use a different answer.

Derek Schultz looks right. The '\ b' character moves the print cursor back one character, allowing you to overwrite the character printed there (it does not delete the entire line or even the character that was there if you are not printing new information on top). The following is an example of a progress bar using Java, although it does not fit your format, it shows how to solve the main problem of character rewriting (this was tested only on Ubuntu 12.04 with Oracle Java 7 on a 32-bit machine, but it should work on all Java -systems):

 public class BackSpaceCharacterTest { // the exception comes from the use of accessing the main thread public static void main(String[] args) throws InterruptedException { /* Notice the user of print as opposed to println: the '\b' char cannot go over the new line char. */ System.out.print("Start[ ]"); System.out.flush(); // the flush method prints it to the screen // 11 '\b' chars: 1 for the ']', the rest are for the spaces System.out.print("\b\b\b\b\b\b\b\b\b\b\b"); System.out.flush(); Thread.sleep(500); // just to make it easy to see the changes for(int i = 0; i < 10; i++) { System.out.print("."); //overwrites a space System.out.flush(); Thread.sleep(100); } System.out.print("] Done\n"); //overwrites the ']' + adds chars System.out.flush(); } } 
+9
Dec 31 '13 at 17:35
source share

You can print the backspace character '\ b' as many times as necessary to delete the line before printing the updated execution line.

+2
Oct 29 '11 at 15:34
source share



All Articles