78

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?

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • 3
    What do you mean by "delete"? Do you mean it created a file somewhere and you want to delete that? Or you want the program not to output the data to the console? Or... something else? You haven't provided anywhere near enough information for anyone to understand what you want, much less help you. Explain how you invoke the program, and where the "stuff" you want deleted is. – Jim Garrison Sep 22 '11 at 22:07
  • 3
    You mean you want to delete System.out.println() calls from your code? OR you want that code untouched, but nothing written to sysout although code executes System.out.println()? Unix/Windows? – Kashyap Sep 22 '11 at 22:08
  • 2
    Lesson learned: Don't print to standard out :D Next time use a [Logger](http://download.oracle.com/javase/6/docs/api/java/util/logging/package-summary.html) – Nate W. Sep 22 '11 at 22:09
  • I want to delete the content from the console, the terminal, the screen. –  Sep 22 '11 at 22:12
  • 1
    Clear the content , i guess is what he want – Rami Alshareef Sep 22 '11 at 22:13
  • Yes exactly. I want something like cls respectively clear but programatically. –  Sep 22 '11 at 22:15
  • Java does not support "cls" or "clear" feature. Think of it from another perspective, you can direct your System.out.println to a file, and within the file, the cls or clear doesn't make any sense. You can go native and issue the clear screen command. – Usman Saleem Sep 22 '11 at 22:23

15 Answers15

75

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?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
28

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

LabOctoCat
  • 611
  • 7
  • 17
27

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 {}
}));
lukastymo
  • 26,145
  • 14
  • 53
  • 66
  • Good suggestions. For (c) why do you throw an IOException? As I understand it, the PrintStream will swallow the IOException. – emory Sep 22 '11 at 22:47
  • @emory: Actually it isn't necessary here, I've just created the stub in eclipse and it had inserted me this (it's exactly the same definition like in OutputStream) – lukastymo Sep 22 '11 at 22:53
  • @emory - a more cogent reason to leave out the `throws` is that the method body doesn't throw the exception. But this is all nitpicking. – Stephen C Sep 22 '11 at 23:36
  • Upvote dude, But how do you switch System.setOut, back to normal ? I did not find a System.getOut – taxeeta Jul 21 '13 at 11:20
  • `Runtime.getRuntime().exec("cls");` does not work. See [this answer](https://stackoverflow.com/a/33379766/2711488) for details. – Holger Mar 18 '19 at 16:24
8

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.

akjoshi
  • 15,374
  • 13
  • 103
  • 121
6

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);
}
Andrea
  • 11,801
  • 17
  • 65
  • 72
Jordan King
  • 93
  • 1
  • 6
6

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');
superrcoop
  • 421
  • 5
  • 13
6

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Have you tried `\r`? It makes it possible to jump back to the beginning of the line and create a line with updating information... – Erk Aug 03 '18 at 03:04
  • @Erk: That's similar to [this answer](https://stackoverflow.com/a/7522190/120955) (using `\b`), but `\r` [is interpreted differently by different environments](https://stackoverflow.com/q/9260126/120955). The point of my answer is that even if this works while `System.out` is directed at the console (which is the *default* behavior for Java programs), you shouldn't assume that it will always be directed there. It could be sending things to a file, in which case you'll end up with a file containing the text you wanted to delete followed by special characters. – StriplingWarrior Aug 03 '18 at 15:22
  • You're right of course. Looking at the OP again I realize it was just about deleting println:ed stuff. That it was for some kind of "ticking info bar" was my own interpretation. And, yes, that kind of output will look bad in a file... unless the program you use to print it interprets the \r's like the console... but I guess a text editor wouldn't. – Erk Aug 04 '18 at 00:32
4

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);
    }
HesNotTheStig
  • 549
  • 1
  • 4
  • 9
4

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}

srkavin
  • 1,152
  • 7
  • 17
2

The easiest ways to do this would be:

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

System.out.println("\u000c");
spongebob
  • 8,370
  • 15
  • 50
  • 83
Anon
  • 21
  • 1
2

For intellij console the 0x08 character worked for me!

System.out.print((char) 8);
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
1

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.

sbanders
  • 851
  • 1
  • 9
  • 19
  • @EJP 1) this was from last year, 2) It is a POTENTIAL solution, if he's using eclipse, 3) the accepted answer made mention of Eclipse just as I did – sbanders Mar 20 '15 at 16:46
1

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)

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331
-1

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.

mxk
  • 43,056
  • 28
  • 105
  • 132
  • 2
    This doesn't erase anything. It just prevents it from being output in the first place. Not what was asked for. Also incomplete. – user207421 Mar 12 '15 at 09:12
-1

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");
Ankit Jha
  • 1
  • 1