sadia
¿Alguien puede decirme qué código se usa para borrar la pantalla en Java?
Por ejemplo, en C++:
system("CLS");
¿Qué código se usa en Java para borrar la pantalla?
Holger
Dado que aquí hay varias respuestas que muestran un código que no funciona para Windows, aquí hay una aclaración:
Runtime.getRuntime().exec("cls");
Este comando hace no trabajo, por dos razones:
-
No hay un ejecutable llamado
cls.exe
ocls.com
en una instalación estándar de Windows que podría invocarse a través deRuntime.exec
como el conocido comandocls
está integrado en el intérprete de línea de comandos de Windows. -
Al lanzar un nuevo proceso a través de
Runtime.exec
, la salida estándar se redirige a una canalización que puede leer el proceso Java inicial. Pero cuando la salida delcls
el comando se redirige, no borra la consola.
Para resolver este problema, tenemos que invocar el intérprete de línea de comandos (cmd
) y dile que ejecute un comando (/c cls
) que permite invocar comandos incorporados. Además, tenemos que conectar directamente su canal de salida al canal de salida del proceso Java, que funciona a partir de Java 7, usando inheritIO()
:
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Ahora, cuando el proceso de Java está conectado a una consola, es decir, se ha iniciado desde una línea de comandos sin redirección de salida, borrará la consola.
-
¿Por qué esto no funciona para mí? Ejecuto el programa en Windows CMD pero la pantalla no se borra
– Alist3r
22 de marzo de 2016 a las 14:23
satisfacer
Puede usar el siguiente código para borrar la consola de línea de comandos:
clearScreen vacío vacío público () { System.out.print("\033[H\033[2J");
System.out.flush();
}
Caveats:
- This will work on terminals that support ANSI escape codes
- It will not work on Windows’ CMD
- It will not work in the IDE’s terminal
For further reading visit this
-
Care to add to this at all? What is this string and do you need to flush if autoflush is enabled?
– cossacksmanNov 3, 2015 at 0:24
-
They are ANSI escape codes. Specifically clear screen, followed by home. But why is ‘home’ necessary?
– jdurstonNov 12, 2015 at 20:01
-
@jdurston omitting home will not reset the cursor back to the top of the window.
– user3714134Sep 21, 2016 at 11:35
-
Doesn’t work in Eclipse, but work in Linux terminal. One vote for you
– Anh TuanNov 7, 2016 at 9:15
-
This only works if the terminal emulator in which Java runs, supports ANSI escape codes. Windows NT/XP/7/8/10 CMD doesn’t
– Thorbjørn Ravn AndersenSep 17, 2017 at 23:16
Dyndrilliac
This is how I would handle it. This method will work for the Windows OS case and the Linux/Unix OS case (which means it also works for Mac OS X).
public final static void clearConsole()
{
try
{
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
{
Runtime.getRuntime().exec("cls");
}
else
{
Runtime.getRuntime().exec("clear");
}
}
catch (final Exception e)
{
// Handle any exceptions.
}
}
⚠️ Note that this method generally will not clear the console if you are running inside an IDE.
-
On Windows 8.1:
java.io.IOException: Cannot run program "cls": CreateProcess error=2, The system cannot find the file specified
– Ky –Oct 21, 2014 at 20:30
-
@BenLeggiero That error occurs if for some reason the cls command isn’t found by the JVM within some directory from the PATH environment variable. All this code does is call the Windows or Unix system command based on the default system configuration to clear the command prompt or terminal window respectively. It should be exactly the same as opening a terminal window and typing “cls” followed by the Enter key.
– DyndrilliacOct 21, 2014 at 22:34
-
There is no
cls
executable in Windows. It is an internal command ofcmd.exe
.– a_horse_with_no_nameMar 26, 2015 at 13:35
-
As said by others, doesn’t work at all, not only because Windows has no cls executable, but also because the output of subprocesses gets redirected.
– HolgerOct 27, 2015 at 22:55
-
This answer is also a topic on meta see: meta.stackoverflow.com/questions/308950/…
– Petter FribergOct 28, 2015 at 20:35
Bhuvanesh Waran
Try the following :
System.out.print("\033\143");
This will work fine in Linux environment
A way to get this can be print multiple end of lines (“\n”) and simulate the clear screen. At the end clear, at most in the unix shell, not removes the previous content, only moves it up and if you make scroll down can see the previous content.
Here is a sample code:
for (int i = 0; i < 50; ++i) System.out.println();
-
A faster way to accomplish this is printing a single string of 50
\r\n
with a singleprintln
, since there’s a noticeable delay betweenprintln
calls.– Ky –Oct 22, 2014 at 20:01
-
How do you know how many lines the console is configured to display? Might work in most cases, but not all.
– CypherOct 28, 2015 at 20:47
-
The biggest difference between this and a proper
clear
is that in the latter, the new output will be at the top of the screen and not the bottom.– ndm13Jul 12, 2016 at 1:50
-
System.out.println(new String(new char[50]).reemplazar("\0", "\r\n"));
hará el trabajo más rápido y mejor.– Aarón Esaú
30 de diciembre de 2017 a las 0:28
-
@AaronEsau comenzando con JDK 11, puede usar
System.out.println(System.lineSeparator().repeat(50));
– Holger
13 de noviembre de 2019 a las 17:30
Comunidad
Crea un método en tu clase como este: [as @Holger said here.]
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
Esto funciona al menos para Windows, no he comprobado Linux hasta ahora. Si alguien lo comprueba para Linux, hágamelo saber si funciona (o no).
Como método alternativo es escribir este código en clrscr()
:
for(int i = 0; i < 80*300; i++) // Default Height of cmd is 300 and Default width is 80
System.out.print("\b"); // Prints a backspace
No te recomendaré que uses este método.
-
Una forma más rápida de lograr esto es imprimir una sola cadena de 50
\r\n
con un soloprintln
ya que hay un retraso notable entreprintln
llamadas– Ky-
22/10/2014 a las 20:01
-
¿Cómo sabe cuántas líneas está configurada para mostrar la consola? Podría funcionar en la mayoría de los casos, pero no en todos.
– Cifrar
28/10/2015 a las 20:47
-
La mayor diferencia entre esto y una adecuada
clear
es que en este último, la nueva salida estará en la parte superior de la pantalla y no en la parte inferior.– ndm13
12 de julio de 2016 a las 1:50
-
System.out.println(new String(new char[50]).replace("\0", "\r\n"));
hará el trabajo más rápido y mejor.– Aarón Esaú
30 de diciembre de 2017 a las 0:28
-
@AaronEsau comenzando con JDK 11, puede usar
System.out.println(System.lineSeparator().repeat(50));
– Holger
13 de noviembre de 2019 a las 17:30
Neurona
Si desea una forma más independiente del sistema de hacer esto, puede usar el Línea J biblioteca y ConsoleReader.clearScreen()
. Comprobación prudente de si Se admiten JLine y ANSI en el entorno actual probablemente también valga la pena hacerlo.
Algo como el siguiente código funcionó para mí:
import jline.console.ConsoleReader;
public class JLineTest
{
public static void main(String... args)
throws Exception
{
ConsoleReader r = new ConsoleReader();
while (true)
{
r.println("Good morning");
r.flush();
String input = r.readLine("prompt>");
if ("clear".equals(input))
r.clearScreen();
else if ("exit".equals(input))
return;
else
System.out.println("You typed '" + input + "'.");
}
}
}
Al ejecutar esto, si escribe ‘borrar’ en el indicador, se borrará la pantalla. Asegúrese de ejecutarlo desde una terminal/consola adecuada y no en Eclipse.
stackoverflow.com/questions/606086/…
– vanuano
2 de febrero de 2011 a las 20:07