如何打印到同一行?

我想像这样打印进度条:


[#                    ] 1%

[##                   ] 10%

[##########           ] 50%

但是这些都应该打印到终端的同一行,而不是新行。我的意思是,每个新行都应替换上一行,而不是使用print()代替println()。


如何用Java做到这一点?


呼啦一阵风
浏览 818回答 3
3回答

Cats萌萌

格式化字符串,如下所示:[#                    ] 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?)。

慕森王

首先,我很抱歉提出这个问题,但我认为它可以使用另一个答案。德里克·舒尔茨(Derek Schultz)是对的。'\ b'字符将打印光标向后移动一个字符,使您可以覆盖在那里打印的字符(除非您在顶部打印新信息,否则它不会删除整行甚至是那里的字符)。以下是使用Java的进度条的示例,尽管它不遵循您的格式,但显示了如何解决覆盖字符的核心问题(仅在32位计算机上的Ubuntu 12.04中使用Oracle Java 7进行了测试,但它应可在所有Java系统上使用):public class BackSpaceCharacterTest{&nbsp; &nbsp; // the exception comes from the use of accessing the main thread&nbsp; &nbsp; public static void main(String[] args) throws InterruptedException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; /*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Notice the user of print as opposed to println:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; the '\b' char cannot go over the new line char.&nbsp; &nbsp; &nbsp; &nbsp; */&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Start[&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]");&nbsp; &nbsp; &nbsp; &nbsp; System.out.flush(); // the flush method prints it to the screen&nbsp; &nbsp; &nbsp; &nbsp; // 11 '\b' chars: 1 for the ']', the rest are for the spaces&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("\b\b\b\b\b\b\b\b\b\b\b");&nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(500); // just to make it easy to see the changes&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i < 10; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("."); //overwrites a space&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(100);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("] Done\n"); //overwrites the ']' + adds chars&nbsp; &nbsp; &nbsp; &nbsp; System.out.flush();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP