使用java写入控制台窗口中的相同位置

Write to same location in a console window with java(使用java写入控制台窗口中的相同位置)
本文介绍了使用java写入控制台窗口中的相同位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想在控制台窗口的同一位置写入一个字符.

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写入控制台窗口中的相同位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)