简体   繁体   English

如何从控制台删除所有字符?

[英]How can I erase all the characters from the console?

I want my program to be able to erase all the text it's printed. 我希望我的程序能够擦除其打印的所有文本。 Every time it prints something, I call my print() method instead of System.out.print() , but then when I call the erase() method it doesn't seem to do anything in the Windows 7 console. 每次打印某些内容时,我都调用print()方法而不是System.out.print() ,但是当我调用erase()方法时,它似乎在Windows 7控制台中什么也没做。 I can't figure out what's up; 我不知道怎么回事。 I ran a test separately that confirmed that \\b does erase characters but for whatever reason it won't work in erase() . 我单独运行了一个测试,确认\\b确实会擦除字符,但是无论出于何种原因,它都不会在erase()起作用。 Are the backspace characters erasing each other or something? 退格字符是否会相互擦除?

EDIT: I've run some more tests. 编辑:我已经运行了更多的测试。 It looks like \\b won't overwrite newline characters. 看来\\ b不会覆盖换行符。 So I guess I need a way to do that. 所以我想我需要一种方法来做到这一点。

public static int textLength = 0;

public static void erase() {
    for (int i = 0; i < textLength; i++) {
        System.out.print('\b');
    }
    textLength = 0;
}

public static void print(String s) {
    textLength += s.length();
    System.out.print(s);
}
Runtime.getRuntime().exec("cls");

EDIT : Seems like this is not the solution you are looking for. 编辑 :似乎这不是您正在寻找的解决方案。 When using 使用时

System.out.print('\b');

you need to be aware that this does not erase what was already printed. 您需要注意,这不会删除已经打印的内容。 Instead each backspace moves your cursor back one character. 而是每个退格键将光标移回一个字符。 To then actually erase what is there you need to overwrite it with some other text. 要真正擦除那里的内容,您需要用其他一些文本覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM