4

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
specializt
  • 1,913
  • 15
  • 26
Chandra Shekhar
  • 664
  • 2
  • 9
  • 24

4 Answers4

8

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):

enter image description here

howlger
  • 31,050
  • 11
  • 59
  • 99
4

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.

Community
  • 1
  • 1
E-Riz
  • 31,431
  • 9
  • 97
  • 134
3

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();
    }
}
0

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.
KVS
  • 19
  • 1