Java: Clear the console

Java

I have output in my Java console from running an application, how I can i clear it using code ?


If you want to unleash your potential in this competitive field, please visit the Java course page for more information, where you can find the Java tutorials and Java frequently asked interview questions and answers as well.

2
Answers

Replies

The below code will help you clear the screen.


public static void clearScreen() {  


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


    System.out.flush(); 


}

 

There are several ways to clear the console in java but we will see the simplest code.


We pass command line interpreter(cmd) in the ProcessBuilder constructor to clear the console and the interpreter tells it to run a command that permits to call in-built commands (cls).


With the help of an example we will see the code of clearing the console are given below:


For Example:


import java.util.*;

class ClearConsole

{

    public static void main(String[] args)

    {

       // Creates a LinkedList object

        LinkedList ll = new LinkedList();

        

        // To add an elements in LinkedList

        ll.add("C");

        ll.add("C++");

        ll.add("PHP");

        ll.add("JAVA");

        

        // Display LinkedList on the Console

        System.out.println("LinkedList = "+ll);

        

        // Call clsConsole method

        clsConsole();

    }

    

    // Create another static method named

    // clsConsole that contains code of

    // clearing console

    public static void clsConsole(){

        try{

            

            new ProcessBuilder("cmd","/c","cls")

            .inheritIO().start()

            .waitFor();

        }catch(Exception ex){

            ex.printStackTrace();

        }

    }

   

}

In the code above, we have created a LinkedList and added some elements in the list and then it displays LinkedList onto the console using output statement and then after we call clsConsole() method so it clear the console immediately.

 
 

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.

Leave a reply

Before proceeding, please check your email for a verification link. If you did not receive the email, click here to request another.
WhatsApp
To Top