如何打印到同一行?

Ail*_*lyn 57 java

我想打印一个进度条,如下所示:

[#                    ] 1%
[##                   ] 10%
[##########           ] 50%
Run Code Online (Sandbox Code Playgroud)

但是这些应该全部打印到终端中的同一行而不是新行.我的意思是每个新行应该取代之前的,它不是用于print()代替println().

我怎么能用Java做到这一点?

NPE*_*NPE 85

像这样格式化字符串:

[#                    ] 1%\r
Run Code Online (Sandbox Code Playgroud)

注意这个\r角色.这就是所谓的回车,它会将光标移回到行的开头.

最后,请确保使用

System.out.print()
Run Code Online (Sandbox Code Playgroud)

并不是

System.out.println()
Run Code Online (Sandbox Code Playgroud)

  • 由于2004年报告的[旧bug](https://bugs.eclipse.org/bugs/show_bug.cgi?id=76936)尚未修复,因此回车转义序列`\ r`在Eclipse中不起作用在最新版本的Eclipse中(4.3.2 Kepler) (14认同)
  • @MarcoLackovic Eclipse 中的错误已修复(自 2020 年 3 月起)。正如 /sf/answers/4347567871/ 中所指出的,您基本上需要 Window ➺ Preferences ➺ Run/Debug ➺ Console,然后选中两个复选框“Interpret ASCII...”和“Interpret Carriage”返回 (\r) as' (3认同)
  • @Krige:Netbeans 8中的输出窗格也是如此,至少在我的Mac上是这样.`\ r`字符被解释为换行符.遗憾的是,VT100代码和退格也无法正常工作. (2认同)

Kir*_*ill 14

在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)");
Run Code Online (Sandbox Code Playgroud)

有光标导航,清除屏幕等代码.

我认为有一些库可以帮助它(ncurses?).

  • 我已经编写了几个实用程序类来为您自动执行此任务; 它们还包括对产量进行着色:http://bitbucket.org/dainkaplan/tempura-utils (3认同)

Amn*_*ep7 11

首先,我想为重新提出这个问题而道歉,但我觉得它可以使用另一个答案.

德里克舒尔茨是正确的.'\ b'字符将打印光标向后移动一个字符,允许您覆盖在那里打印的字符(它不会删除整行,甚至不删除那里的字符,除非您在上面打印新信息).以下是使用Java的进度条的示例,虽然它不遵循您的格式,它显示了如何解决覆盖字符的核心问题(这仅在Ubuntu 12.04中使用Oracle的Java 7在32位机器上进行了测试,但它应该适用于所有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();
    }
}
Run Code Online (Sandbox Code Playgroud)