Java 如何返回到控制台中一行的开头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/301759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I return to the start of a line in a console?
提问by
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');
回答by Avi
If you just want to write a new line to the console, you should use the println() method:
如果你只想在控制台写一个新行,你应该使用 println() 方法:
System.out.println(mystuff);
However, this will not delete what is already on the line. Actually, since System.out is a PrintStream, which is a type of OutputStream, that is basically hard to do, although you may find terminal-specific ways to do it.
但是,这不会删除已经上线的内容。实际上,由于 System.out 是一个 PrintStream,它是一种 OutputStream,所以基本上很难做到,尽管您可能会找到特定于终端的方法来做到这一点。
You might have better luck using a Java implementation of a curses library, such as JavaCurses.
使用Curses库的 Java 实现(例如JavaCurses )可能会更好。
回答by izb
My guess (And it is a guess) would be that '\r' does work, but the console you're using doesn't treat it as you'd expect. Which console are you using? If it's something like console output in your IDE, have you tried it on a real command-line instead?
我的猜测(这是一个猜测)是 '\r' 确实有效,但您使用的控制台并没有像您期望的那样对待它。您使用的是哪个控制台?如果它类似于您的 IDE 中的控制台输出,您是否在真正的命令行上尝试过?
回答by mtruesdell
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.
我怀疑您的光标正在移动到行的前面。您已有的文本不会消失,因为您没有用任何东西覆盖它。您可以输出空格来空白该行,然后添加另一个 \r。
I just tested the following on Windows XP and AIX and it works as expected:
我刚刚在 Windows XP 和 AIX 上测试了以下内容,它按预期工作:
public class Foo {
public static void main(String[] args) throws Exception {
System.out.print("old line");
Thread.sleep(3000);
System.out.print("\rnew");
}
}
I get "old line" printed, a 3 second delay, and then "old line" changes to "new line"
我打印“旧行”,延迟 3 秒,然后“旧行”更改为“新行”
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.
我故意让第一行比第二行长,以证明如果你想擦除整行,你必须用空格覆盖结尾。
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:
另请注意,“\b”转义序列将备份 1 个空格,而不是备份到行首。所以如果你只想删除最后 2 个字符,你可以写:
System.out.println("foo\b\bun")
and get "fun".
并获得“乐趣”。