简体   繁体   中英

How can I print to the same line?

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?

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()

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 ?).

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();
    }
}

在打印更新的进度条之前,您可以根据需要多次打印退格字符 '\\b' 以删除该行。

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();
    }
}

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.

可以简单地使用\\r将所有内容保留在同一行中,同时删除该行以前的内容。

You can just do

System.out.print("String");

Instead

System.out.println("String");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM