How can I print to the same line?

Java

Java Problem Overview


I want to print a progress bar like so:

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

But these should all be printed to the same line in the terminal instead of a new one. What I mean by that is that each new line should replace the previous, it's not about using print() instead of println().

How can I do that in Java?

Java Solutions


Solution 1 - Java

Format your string like so:

[#                    ] 1%\r

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

Finally, make sure you use

System.out.print()

and not

System.out.println()

Solution 2 - Java

In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K and for move cursor to previous line: \33[1A. So all you need is to print this every time you need to refresh the line. Here is the code which 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, clearing screen and so on.

I think there are some libraries which helps with it (ncurses?).

Solution 3 - Java

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's 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();
	}
}

Solution 4 - Java

You could print the backspace character '\b' as many times as necessary to delete the line before printing the updated progress bar.

Solution 5 - Java

package org.surthi.tutorial.concurrency;

public class IncrementalPrintingSystem {
    public static void main(String...args) {
        new Thread(()-> {
           int i = 0;
           while(i++ < 100) {
               System.out.print("[");
               int j=0;
               while(j++<i){
                  System.out.print("#");
               }
               while(j++<100){
                  System.out.print(" ");
               }
               System.out.print("] : "+ i+"%");
               try {
                  Thread.sleep(1000l);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
               System.out.print("\r");
           }
        }).start();
    }
}

Solution 6 - Java

In kotlin

print()

The print statement prints everything inside it onto the screen. The print statements internally call System.out.print.

println()

The println statement appends a newline at the end of the output.

Solution 7 - Java

One could simply use \r to keep everything in the same line while erasing what was previously on that line.

Solution 8 - Java

You can just do

System.out.print("String");

Instead

System.out.println("String");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAillynView Question on Stackoverflow
Solution 1 - JavaNPEView Answer on Stackoverflow
Solution 2 - JavaKirillView Answer on Stackoverflow
Solution 3 - JavaAmndeep7View Answer on Stackoverflow
Solution 4 - JavaDerek SchultzView Answer on Stackoverflow
Solution 5 - JavaRavi SurthiView Answer on Stackoverflow
Solution 6 - JavaAjay DeepakView Answer on Stackoverflow
Solution 7 - JavaAmiothenesView Answer on Stackoverflow
Solution 8 - JavaMosrurView Answer on Stackoverflow