java clear console

java clear console

In Java, you can clear the console by using the System.out.print method to output a series of blank lines.

Here's an example of how to clear the console in Java:

re‮:ot ref‬lautturi.com
public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
      System.out.println();  // output a blank line
    }
  }
}

In this example, the for loop outputs 100 blank lines, effectively clearing the console. You can adjust the number of blank lines to suit your needs.

Keep in mind that this method only works if the console supports scrolling. If the console does not support scrolling, the output will be overwritten but the previous output will still be visible.

Alternatively, you can use the clear command on the command line to clear the console. This method works on most operating systems and is more reliable, but it requires access to the command line.

For example, on Windows you can use the cls command to clear the console:

public class Main {
  public static void main(String[] args) {
    try {
      new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

On Linux or macOS, you can use the clear command to clear the console:

public class Main {
  public static void main(String[] args) {
    try {
      new ProcessBuilder("clear").inheritIO().start().waitFor();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Keep in mind that using the ProcessBuilder class to execute commands on the command line is a potentially dangerous operation, as it can allow the program to execute arbitrary code. You should use this method with caution and only in controlled environments.

Created Time:2017-11-03 00:14:50  Author:lautturi