如何在控制台中返回到行的开头? [英] How can I return to the start of a line in a console?

查看:148
本文介绍了如何在控制台中返回到行的开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回行的开头并覆盖控制台上已输出的内容?以下似乎不起作用:

How can I return to the start of a line and overwrite what has already been output on the console? The following does not appear to work:

System.out.print(mystuff+'\r');


推荐答案

我怀疑你的光标正在移动到前面这条线。你已经拥有的文字并没有消失,因为你没有用任何东西覆盖它。您可以输出空格以清空该行,然后添加另一个\ r。

I suspect that your cursor IS moving to the front of the line. The text you already have isn't disappearing because you haven't overwritten it with anything. You could output spaces to blank the line and then add another \r.

我刚刚在Windows XP和AIX上测试了以下内容,它按预期工作:

I just tested the following on Windows XP and AIX and it works as expected:

public class Foo {
  public static void main(String[] args) throws Exception {
   System.out.print("old line");
   Thread.sleep(3000);
   System.out.print("\rnew");
  }
}

我打印旧线,3秒延迟,然后旧行更改为新行

I get "old line" printed, a 3 second delay, and then "old line" changes to "new line"

我故意使第一行比第二行更长,以证明如果要删除整行你必须用空格覆盖结尾。

I intentionally made the first line longer than the second to demonstrate that if you want to erase the whole line you'd have to overwrite the end with spaces.

另请注意,\ b转义序列将备份1个空格,而不是开头的空格。线。所以如果你只想删除最后2个字符,你可以写:

Also note that the "\b" escape sequence will back up 1 space, instead of to the beginning of the line. So if you only wanted to erase the last 2 characters, you could write:

System.out.println("foo\b\bun")

并获得乐趣。

这篇关于如何在控制台中返回到行的开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆