What command in Java will let you clear the console in a command-line application?
There are two very simple ways to solve this, the first is the brute force option:
for (int i=1; i<=10; i++)
System.out.println("\n");
The problem with this however is that it only pseudo clears the screen, you can scroll up to see the data, but don't fear, there is another way!
System.out.println("\f");
Voila! That should do the trick, although your cursor will be situated on the second line of the console after the screen is cleared.
System.out.println("Hello!");
prints the specified string and then moves the cursor to the next line.
System.out.print("Hello!");
prints the specified string and leaves the cursor immediately after that string.
To solve the problem, identified above, of the cursor being on the second line of the console, use print
instead of println
.
Clearing a screen generally requires sending special control sequences specific to the screen/terminal that your application is running under. Options:
If you know you will always running under a specific terminal and can find the proper control sequences to clear the screen for that terminal, just output those sequences. If you tell us the screen, we may be able to tell you the sequence (its likely somewhat ANSI/VT100/VT220 -compatible).
Externally ensure your app is always run in a desired terminal, e.g. a script to start your app starts the app in the desired terminal. Then output the necessary character sequence to clear the screen.
Take control of the terminal by using a terminal emulation library, i.e. you app is now a windowing app that creates a terminal window screen for the user to use. You then control what terminal you are emulating and will know what control sequences are needed.
Use a terminal library (e.g. like the historic curses
library) that detects the terminal and provides an uniform interface to its features. See this question:
What's a good Java, curses-like, library for terminal applications?
Fake it by writing a bunch of lines to the screen.
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");
I did this in BlueJ and it worked perfectly: Try System.out.print("\f");