簡體   English   中英

如何打印到同一行?

[英]How can I print to the same line?

我想像這樣打印一個進度條:

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

但是這些都應該打印到終端的同一行而不是新的一行。 我的意思是每個新行都應該替換前一行,這與使用print()而不是println()無關。

我怎樣才能在 Java 中做到這一點?

像這樣格式化你的字符串:

[#                    ] 1%\r

注意\\r字符。 就是將光標移回行首的所謂回車

最后,請確保您使用

System.out.print()

並不是

System.out.println()

在 Linux 中,控制終端有不同的轉義序列。 例如,擦除整行有特殊的轉義序列: \\33[2K和將光標移動到上一行: \\33[1A 所以你需要做的就是在每次需要刷新行時打印它。 這是打印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)");

有光標導航、清屏等代碼。

我認為有一些庫可以幫助它( ncurses ?)。

首先,我想為重新提出這個問題而道歉,但我覺得它可以使用另一個答案。

德里克舒爾茨是正確的。 '\\b' 字符將打印光標向后移動一個字符,允許您覆蓋在那里打印的字符(它不會刪除整行甚至是那里的字符,除非您在頂部打印新信息)。 下面是一個使用 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();
    }
}

在科特林

print()

打印語句將其中的所有內容打印到屏幕上。 打印語句在內部調用System.out.print

println()

println 語句在輸出的末尾附加一個換行符。

可以簡單地使用\\r將所有內容保留在同一行中,同時刪除該行以前的內容。

你可以做

System.out.print("String");

反而

System.out.println("String");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM