简体   繁体   English

如何打印到同一行?

[英]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() .我的意思是每个新行都应该替换前一行,这与使用print()而不是println()无关。

How can I do that in Java?我怎样才能在 Java 中做到这一点?

Format your string like so:像这样格式化你的字符串:

[#                    ] 1%\r

Note the \\r character.注意\\r字符。 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.在 Linux 中,控制终端有不同的转义序列。 For example, there is special escape sequence for erase whole line: \\33[2K and for move cursor to previous line: \\33[1A .例如,擦除整行有特殊的转义序列: \\33[2K和将光标移动到上一行: \\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) :这是打印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 ?).我认为有一些库可以帮助它( 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). '\\b' 字符将打印光标向后移动一个字符,允许您覆盖在那里打印的字符(它不会删除整行甚至是那里的字符,除非您在顶部打印新信息)。 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):下面是一个使用 Java 的进度条示例,虽然它不遵循您的格式,但它展示了如何解决覆盖字符的核心问题(这仅在 32 位机器上使用 Oracle 的 Java 7 的 Ubuntu 12.04 中进行了测试,但它应该适用于所有 Java 系统):

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 .打印语句在内部调用System.out.print

println()

The println statement appends a newline at the end of the output. println 语句在输出的末尾附加一个换行符。

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

You can just do你可以做

System.out.print("String");

Instead反而

System.out.println("String");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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