How to clear console in Java - Eclipse

社会主义新天地 提交于 2020-01-11 06:24:54

问题


How to clear the console after a few statements have been executed/printed in Eclipse. I have used flush() but didn't work though. Just posting the sample code.

System.out.println("execute ");
System.out.println("these set of lines ");
System.out.println("first");

Thread.sleep(2000); // just to see the printed statements in the console
System.out.flush(); // it is not clearing the above statements

回答1:


System.out is a Stream, it makes no sense to clear a stream.

Eclipse's Console is a view that renders that stream and has richer capabilities (including the ability to clear its visible buffer of the stream's content) but the only way to access that is if you were writing an Eclipse plug-in; general Java code has no knowledge of Eclipse's Console view.

You might be able to achieve something moderately useful via some hacks, but I would not recommend relying on it. Usage of System.out in production code is highly discouraged anyway; use a Logger (such as slf4j and logback) instead. And consider what you're really trying to achieve.




回答2:


It depends on your console but if it supports ANSI escape sequences, then try this..

final static String ESC = "\033[";
System.out.print(ESC + "2J"); 

Also, you can print multiple end of lines ("\n") and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.

Here is a sample code:

for (int i = 0; i < 50; ++i) System.out.println();

A third option:

import java.io.IOException;

public class CLS {
    public static void main(String... arg) throws IOException, InterruptedException {
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    }
}



回答3:


The Eclipse Console does not support the interpretation of the clear screen and other ANSI escape sequences which would be required for that. Also, the ANSI Escape in Console Eclipse plug-in does not support clear screen.

In the upcoming Eclipse IDE 2019-12 (4.14) which will be released on December 18, 2019, the interpretation of the backslash (\b) and carriage return (\r) characters can be enabled in the preferences (see Eclipse 4.14 - New and Noteworthy - Control character interpretation in Console View):




回答4:


In case you are talking about eclipse (java console, there is mvn console and svn console as well) then you might want to work with preferences like below:

  1. Go to Window » Preferences to show the Preferences dialog
  2. Go to Run/debug and expand it
  3. Select Console
  4. Here you can now set the console related properties.


来源:https://stackoverflow.com/questions/37301530/how-to-clear-console-in-java-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!