我想打印一个进度条,如下所示:
[# ] 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)
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
?).
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)
归档时间: |
|
查看次数: |
129691 次 |
最近记录: |