问题描述
我想在控制台窗口的同一位置写入一个字符.
I would like to write a character to the same location in a console window.
我想写的字符是/ - _.这会给我一个小微调器,我可以显示进度或加载.
The characters I would like to write are / - _. This will get me a little spinner I can display to show progress or loading.
你怎么能把字符写到同一个位置呢?否则,你会得到类似这样的 /-\_/-\_/-
How can you write the chars to the same location though? Otherwise, you will wind up with something like this /-\_/-\_/-
推荐答案
在 Java 6 中,您可以使用 Console 来做这样的事情:
With Java 6 you can use the Console to do something like this:
class Main {
public static void main(String[] args) throws InterruptedException {
String[] spinner = new String[] {"u0008/", "u0008-", "u0008\", "u0008|" };
Console console = System.console();
console.printf("|");
for (int i = 0; i < 1000; i++) {
Thread.sleep(150);
console.printf("%s", spinner[i % spinner.length]);
}
}
}
u0008 是特殊的退格字符.删除行上最后一个字符的打印.通过开始打印 | 然后在所有其他字符之前添加 u0008 ,您将获得微调器行为.
u0008 is the special backspace character. Printing that erases the last character on the line. By starting to print a | and then prepending the u0008 before all other characters you get the spinner behavior.
请注意,这可能并非 100% 兼容所有控制台(并且 System.console() 可以返回 null).
Note that this might not be 100% compatible with all consoles (and that System.console() can return null).
还请注意,您不一定必须使用控制台类,因为将此序列打印到标准输出通常也可以.
Also note that you don't necessarily have to use the console class, as printing this sequence to standard output commonly works just as well.
这篇关于使用java写入控制台窗口中的相同位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)