如何在控制台中返回到行首?

2022-01-11 00:00:00 console java

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

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+'');

推荐答案

我怀疑您的光标正在移动到行首.你已经拥有的文本并没有消失,因为你没有用任何东西覆盖它.您可以输出空格以空白行,然后添加另一个 .

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 .

我刚刚在 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("new");
  }
}

我打印出旧行",延迟 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.

还请注意,"转义序列将备份 1 个空格,而不是到行首.所以如果你只想擦除最后 2 个字符,你可以写:

Also note that the "" 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("fooun")

并获得乐趣".

相关文章