[java] How to delete stuff printed to console by System.out.println()?

In a Java application I'm using some calls to System.out.println(). Now I want to find a way to programmatically delete this stuff.

I couldn't find any solution with google, so are there any hints?

This question is related to java

The answer is


I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:-

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

this will clear whatever is printed before this line. But this does not work in command prompt.


I've found that in Eclipse Mars, if you can safely assume that the line you replace it with will be at least as long as the line you are erasing, simply printing '\r' (a carriage return) will allow your cursor to move back to the beginning of the line to overwrite any characters you see. I suppose if the new line is shorter, you can just make up the different with spaces.

This method is pretty handy in eclipse for live-updating progress percentages, such as in this code snippet I ripped out of one of my programs. It's part of a program to download media files from a website.

    URL url=new URL(link);
    HttpURLConnection connection=(HttpURLConnection)url.openConnection();
    connection.connect();
    if(connection.getResponseCode()!=HttpURLConnection.HTTP_OK)
    {
        throw new RuntimeException("Response "+connection.getResponseCode()+": "+connection.getResponseMessage()+" on url "+link);
    }
    long fileLength=connection.getContentLengthLong();
    File newFile=new File(ROOT_DIR,link.substring(link.lastIndexOf('/')));
    try(InputStream input=connection.getInputStream();
        OutputStream output=new FileOutputStream(newFile);)
    {
        byte[] buffer=new byte[4096];
        int count=input.read(buffer);
        long totalRead=count;
        System.out.println("Writing "+url+" to "+newFile+" ("+fileLength+" bytes)");
        System.out.printf("%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        while(count!=-1)
        {
            output.write(buffer,0,count);
            count=input.read(buffer);
            totalRead+=count;
            System.out.printf("\r%.2f%%",((double)totalRead/(double)fileLength)*100.0);
        }
        System.out.println("\nFinished index "+INDEX);
    }

Just to add to BalusC's anwswer...

Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6}


Clearing screen in Java is not supported, but you can try some hacks to achieve this.

a) Use OS-depends command, like this for Windows:

Runtime.getRuntime().exec("cls");

b) Put bunch of new lines (this makes ilusion that screen is clear)

c) If you ever want to turn off System.out, you can try this:

System.setOut(new PrintStream(new OutputStream() {
    @Override public void write(int b) throws IOException {}
}));

For intellij console the 0x08 character worked for me!

System.out.print((char) 8);

The easiest ways to do this would be:

System.out.println("\f");

System.out.println("\u000c");

I have successfully used the following:

@Before
public void dontPrintExceptions() {
    // get rid of the stack trace prints for expected exceptions
    System.setErr(new PrintStream(new NullStream()));
}

NullStream lives in the import com.sun.tools.internal.xjc.util package so might not be available on all Java implementations, but it's just an OutputStream, should be simple enough to write your own.


You could print the backspace character \b as many times as the characters which were printed before.

System.out.print("hello");
Thread.sleep(1000); // Just to give the user a chance to see "hello".
System.out.print("\b\b\b\b\b");
System.out.print("world");

Note: this doesn't work flawlessly in Eclipse console in older releases before Mars (4.5). This works however perfectly fine in command console. See also How to get backspace \b to work in Eclipse's console?


I found a solution for the wiping the console in an Eclipse IDE. It uses the Robot class. Please see code below and caption for explanation:

   import java.awt.AWTException;
   import java.awt.Robot;
   import java.awt.event.KeyEvent;

   public void wipeConsole() throws AWTException{
        Robot robbie = new Robot();
        //shows the Console View
        robbie.keyPress(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyRelease(KeyEvent.VK_ALT);
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_Q);
        robbie.keyPress(KeyEvent.VK_C);
        robbie.keyRelease(KeyEvent.VK_C);

        //clears the console
        robbie.keyPress(KeyEvent.VK_SHIFT);
        robbie.keyPress(KeyEvent.VK_F10);
        robbie.keyRelease(KeyEvent.VK_SHIFT);
        robbie.keyRelease(KeyEvent.VK_F10);
        robbie.keyPress(KeyEvent.VK_R);
        robbie.keyRelease(KeyEvent.VK_R);
    }

Assuming you haven't changed the default hot key settings in Eclipse and import those java classes, this should work.


There are two different ways to clear the terminal in BlueJ. You can get BlueJ to automatically clear the terminal before every interactive method call. To do this, activate the 'Clear screen at method call' option in the 'Options' menu of the terminal. You can also clear the terminal programmatically from within your program. Printing a formfeed character (Unicode 000C) clears the BlueJ terminal, for example:

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

You could use cursor up to delete a line, and erase text, or simply overwrite with the old text with new text.

int count = 1; 
System.out.print(String.format("\033[%dA",count)); // Move up
System.out.print("\033[2K"); // Erase line content

or clear screen

System.out.print(String.format("\033[2J"));

This is standard, but according to wikipedia the Windows console don't follow it.

Have a look: http://www.termsys.demon.co.uk/vtansi.htm


To clear the Output screen, you can simulate a real person pressing CTRL + L (which clears the output). You can achieve this by using the Robot() class, here is how you can do this:

try {
        Robot robbie = new Robot();
        robbie.keyPress(17); // Holds CTRL key.
        robbie.keyPress(76); // Holds L key.
        robbie.keyRelease(17); // Releases CTRL key.
        robbie.keyRelease(76); // Releases L key.
    } catch (AWTException ex) {
        Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}

BalusC answer didn't work for me (bash console on Ubuntu). Some stuff remained at the end of the line. So I rolled over again with spaces. Thread.sleep() is used in the below snippet so you can see what's happening.

String foo = "the quick brown fox jumped over the fence";
System.out.printf(foo);
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul(" ", foo.length()));
try {Thread.sleep(1000);} catch (InterruptedException e) {}
System.out.printf("%s", mul("\b", foo.length()));

where mul is a simple method defined as:

private static String mul(String s, int n) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < n ; i++)
        builder.append(s);
    return builder.toString();
}

(Guava's Strings class also provides a similar repeat method)


this solution is applicable if you want to remove some System.out.println() output. It restricts that output to print on console and print other outputs.

PrintStream ps = System.out;
System.setOut(new PrintStream(new OutputStream() {
   @Override
   public void write(int b) throws IOException {}
}));

System.out.println("It will not print");

//To again enable it.
System.setOut(ps);

System.out.println("It will print");

System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically.

I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact.