Java清除控制台

JAVA 中如何清除console的输出

JenningLang 2016-10-26 18:34:22 15728 收藏 3
展开
首先给上答案连接,请看最多赞的答案

http://stackoverflow.com/questions/2979383/java-clear-the-console

一般的帖子里会给出这样的答案

Runtime.getRuntime().exec("cls");
1
然而 Windows 亲自测试这个命令无法运行,会报出如下错误(在Eclipse和CMD中都会这样):

Cannot run program "cls": CreateProcess error=2, 系统找不到指定的文件。
1
出错的原因是有如下两点

在标准的 Windows 安装中并没有叫 cls.exe 或者 cls.com 的可执行程序,而 Runtime.exec 命令正是因为这个原因无法被调用,可以看错误信息“系统找不到制定的文件”。我们所熟知的 cls 命令是 Windows 命令行解释器内嵌的命令(说白了就是 cmd.exe 程序中的命令,而不是 Windows 的命令)

当通过 Runtime.exec 命令进入一个进程后,其标准输出(就是 Runtime.exec 所执行命令的输出)被重定向到了一个新的管道(pipe),这个管道对于原来的 Java 进程也是可见的。但是 cls 命令的输出被重定向没有什么意义,因为 Java 进程所运行的那个窗口并不是执行 cls 命令的窗口(这一条并非出错的原因,但是下面解决办法的原理)

为了解决这一问题,我们必须先启动命令行解释器(cmd.exe)并且告诉 cmd 我们想执行一个清屏操作(/c cls)(这里的 /c 的作用我是这样理解的,实际执行了 cmd /c cls 后,我们看见的命令行已经不是原来的命令行了,而是新打开的命令行,因为这命令的意思是打开一个命令行,清屏并关闭原来的命令行),这样才能使用 cmd 内建的命令;此外,我们也必须将 cmd 的输出通道和 Java 进程的输出通道直接相连接,这个功能从 Java 7 开始被支持,其函数是 inheritIO(),具体代码如下:

import java.io.IOException;

public class CLS {
public static void main(String args[]) throws IOException, InterruptedException {
// ...
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); // 清屏命令
// ...
}
}

关于上面的几句命令我是这样理解的

new ProcessBuilder("cmd", "/c", "cls")
1
就是新建一个 ProcessBuilder,其要执行的命令是 cmd.exe,参数是 /c 和 cls

.inheritIO()
1
这个函数上面介绍了,就是将 ProcessBuilder 对象的输出管道和 Java 的进程进行关联,这个函数的返回值也是一个 ProcessBuilder,但是建立了关联之后的 ProcessBuilder。

.start()
1
开始执行 ProcessBuilder 中的命令

.waitFor()
1
等待 ProcessBuilder 中的命令执行完毕(我猜测可能如果不执行这个等待命令,可能会出现清屏代码后面的输出被清掉的情况,没尝试过)

这样一来当 Java 进程被直接连接到控制台,而没有被重定向,清屏功能就可以实现了。

经过实际测试,在Eclipse 的控制台输出里是不行的(从以上的原理中可以知道其原因,因为这个命令连接到的是 cmd 而不是Eclipse 的控制台),打包成 jar 包,运行 java -jar ***.jar 就可以了(不过偶尔清屏还可以,想实现刷新效果还是差了点,晃眼睛。。。)

PS:其他的还有一个方法没有测试过,代码如下

System.out.print("\033[H\033[2J");
System.out.flush();
1
2
据说这个代码在基于 UNIX 的机子上都能行,不过没试过。在 Linux 上我也没试过如下代码

Runtime.getRuntime().exec("clear");
1
但感觉上应该没问题

---------------------------------------------

java控制台的清屏

ptrlink 2008-09-04 12:25:00 14025 收藏
展开
最近写了个java的定时器程序,因为在C/C++中有system("cls")可以进行清屏,然而在java中却从来没发现过相关功能的方法,在网上搜了很久也没找到成功的解决方案,所有的方案都是带有喜剧性的,1.Runtime.getRuntime().exec("cmd /c cls");但这种是建立子线程,不能控制当前屏幕的清屏,2.就更搞笑了,System.out.println("/n /n /n /n /n /n /n /n /n /n /n /n /n /n /n /n");当然这种方法在某些情况下达到了目的,不过总觉得怪怪的,有点不尽人意3.System.out.println(" /b /b /b /b /b /b /b /b /b /b /b");这个就更搞笑了,呵呵,大家说呢;

 

所以我自己思考了一个方案:

 

要java在windows下的cmd下实现清屏,我想了个方案,就是通过JNI调用一个库文件(.dll),这个dll中包含一个实现清屏功能(system(“cls”))的导出函数。在java程序中加入代码调用这个库,即可实现当前屏幕的清屏。(--JNI的使用,以及dll的制作在百度随便搜索即可找到,这里请恕不多谈^_^--)

 

实现步骤:

1.写一个dll.h

 

#ifndef _Included_Cls
#define _Included_Cls
#ifdef __cplusplus
extern "C"
{
#endif
JNIEXPORT void JNICALL Java_Cls_clear
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif

2.再写一个dllmain.c

 

#include "jni.h"
#include "dll.h"
#include "stdlib.h"
JNIEXPORT void JNICALL Java_Cls_clear(JNIEnv *env, jobject obj)
{
system("cls");
}

 

3.用vc++建立一个dll工程(我的工程名为clsTest)

导入dllmain.c 和dll.h以及jdk下include目录下的jni.h和include/win32下的jni_md.h 共四个文件

然后build 这个dll工程,将生成的clsTest.dll放入到你的java.library.path中的其中一个目录下

查看java.libray.path用代码System.out.print(System.setProperty("java.library.path","."));

我是根据我的配置将clsTest.dll放到C:/Program Files/Java/jdk1.6.0/jre/bin下

4.测试

新建一个测试类Test.java

 

public class Test{
public native void clear();//左方的native是通知Java這個函数会使用到外部函数

static {
System.loadLibrary("clsTest"); //左方的代码代表我要载入clsTest.dll的动态链接

}

public static void main(String[] args) {
final Test a=new Test();

Runnable k=new Runnable(){
public void run(){
for(int i=0;i<20;i++){
System.out.println(i);
try {
Thread.sleep(1000);
a.clear();
} catch (Exception e) {
}

}
}
};
k.run();//执行线程
}
}
5.在cmd下 javac Test.java

java Test

即可看到运行效果^_^~

 

注:该解决方案只解决控制台程序的刷屏,且必须是系统控制台,而eclipse等其它IDE的控制台是无法用这种方式进行清屏的,如果要实现,必须使用入侵IDE的进程,因为在eclipse的内置控制台右击邮件有个clear功能,实际上就是个setText(null)事件,入侵IDE就是要在外部制造这个事件,其它IDE要也差不多。

同样,java的这种刷屏解决方案也适用于linux,不同是其链接库文件是.so,总之原理是差不多的。

-------------------

Java: Clear the console
Ask Question
Asked 9 years, 11 months ago
Active 3 days ago
Viewed 578k times

135
46
Can any body please tell me what code is used for clear screen in Java? For example in C++

system("CLS");
What code is used in Java for clear screen?

Thanks!

java console clear
shareimprove this questionfollow
edited Jun 5 '10 at 11:59

Martijn Courteaux
60.9k4141 gold badges181181 silver badges271271 bronze badges
asked Jun 5 '10 at 6:14

sadia
1,50544 gold badges1515 silver badges1717 bronze badges
1
stackoverflow.com/questions/606086/… – Vanuan Feb 2 '11 at 20:07
add a comment
11 Answers
Active
Oldest
Votes

107

Since there are several answers here showing non-working code for Windows, here is a clarification:

Runtime.getRuntime().exec("cls");
This command does not work, for two reasons:

There is no executable named cls.exe or cls.com in a standard Windows installation that could be invoked via Runtime.exec, as the well-known command cls is builtin to Windows’ command line interpreter.
When launching a new process via Runtime.exec, the standard output gets redirected to a pipe which the initiating Java process can read. But when the output of the cls command gets redirected, it doesn’t clear the console.
To solve this problem, we have to invoke the command line interpreter (cmd) and tell it to execute a command (/c cls) which allows invoking builtin commands. Further we have to directly connect its output channel to the Java process’ output channel, which works starting with Java 7, using 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();
}
}
Now when the Java process is connected to a console, i.e. has been started from a command line without output redirection, it will clear the console.

shareimprove this answerfollow
edited Mar 13 '16 at 5:03

Jeffrey Bosboom
11.3k1313 gold badges6464 silver badges8383 bronze badges
answered Oct 27 '15 at 22:40

Holger
207k2626 gold badges301301 silver badges572572 bronze badges
Why this not work for me? I running the program on windows CMD but the screen its not cleared – Alist3r Mar 22 '16 at 14:23
add a comment

82

You can use following code to clear command line console:

public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
For further references visit: http://techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html

shareimprove this answerfollow
edited Dec 30 '17 at 1:47

Mamun
50.3k99 gold badges2525 silver badges3939 bronze badges
answered Aug 30 '15 at 11:19

satish
1,08377 silver badges33 bronze badges
2
Care to add to this at all? What is this string and do you need to flush if autoflush is enabled? – cossacksman Nov 3 '15 at 0:24
7
They are ANSI escape codes. Specifically clear screen, followed by home. But why is 'home' necessary? – jdurston Nov 12 '15 at 20:01
1
@jdurston omitting home will not reset the cursor back to the top of the window. – Hugo Zink Sep 21 '16 at 11:35
1
Doesn't work in Eclipse, but work in Linux terminal. One vote for you – Anh Tuan Nov 7 '16 at 9:15
6
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 Andersen Sep 17 '17 at 23:16
show 9 more comments

17

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.

shareimprove this answerfollow
edited Apr 25 at 4:18

Basheer AL-MOMANI
9,82966 gold badges7272 silver badges7171 bronze badges
answered Jun 9 '13 at 23:04

Dyndrilliac
63888 silver badges1515 bronze badges
10
On Windows 8.1: java.io.IOException: Cannot run program "cls": CreateProcess error=2, The system cannot find the file specified – Ben Leggiero Oct 21 '14 at 20:30
1
@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. – Dyndrilliac Oct 21 '14 at 22:34
22
There is no cls executable in Windows. It is an internal command of cmd.exe. – a_horse_with_no_name Mar 26 '15 at 13:35
7
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. – Holger Oct 27 '15 at 22:55
2
This answer is also a topic on meta see: meta.stackoverflow.com/questions/308950/… – Petter Friberg Oct 28 '15 at 20:35
show 3 more comments

15

If you want a more system independent way of doing this, you can use the JLine library and ConsoleReader.clearScreen(). Prudent checking of whether JLine and ANSI is supported in the current environment is probably worth doing too.

Something like the following code worked for me:

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 + "'.");

}
}
}
When running this, if you type 'clear' at the prompt it will clear the screen. Make sure you run it from a proper terminal/console and not in Eclipse.

shareimprove this answerfollow
answered Jan 19 '13 at 1:50

prunge
19.1k33 gold badges6565 silver badges7272 bronze badges
add a comment

14

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();
shareimprove this answerfollow
answered Nov 24 '12 at 15:23

blackløtus
79511 gold badge77 silver badges1414 bronze badges
12
A faster way to accomplish this is printing a single string of 50 \r\n with a single println, since there's a noticeable delay between println calls. – Ben Leggiero Oct 22 '14 at 20:01
7
How do you know how many lines the console is configured to display? Might work in most cases, but not all. – Cypher Oct 28 '15 at 20:47
4
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. – ndm13 Jul 12 '16 at 1:50
5
System.out.println(new String(new char[50]).replace("\0", "\r\n")); will do the job faster and better. – Aaron Esau Dec 30 '17 at 0:28
1
@AaronEsau starting with JDK 11, you can use System.out.println(System.lineSeparator().repeat(50)); – Holger Nov 13 '19 at 17:30
show 1 more comment

12

Create a method in your class like this: [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) {}
}
This works for windows at least, I have not checked for Linux so far. If anyone checks it for Linux please let me know if it works (or not).

As an alternate method is to write this code in 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
I will not recommend you to use this method.

shareimprove this answerfollow
edited Dec 31 '17 at 4:45

Community♦
111 silver badge
answered Jul 14 '16 at 5:04

Abhishek Kashyap
1,63511 gold badge99 silver badges1818 bronze badges
add a comment

7

Try the following :

System.out.print("\033\143");
This will work fine in Linux environment

shareimprove this answerfollow
edited Oct 14 '16 at 10:48
answered Oct 14 '16 at 10:42

Bhuvanesh Waran
43599 silver badges2222 bronze badges
add a comment

6

Runtime.getRuntime().exec(cls) did NOT work on my XP laptop. This did -

for(int clear = 0; clear < 1000; clear++)
{
System.out.println("\b") ;
}
Hope this is useful

shareimprove this answerfollow
answered Jun 14 '14 at 17:35

user3648739
9311 silver badge11 bronze badge
if you could set the buffer index location to start this would be the sole easiest approach – DevilInDisguise Feb 5 '16 at 18:12
If the process was to get interrupted, I imagine you'd see lag with some print.out being removed before others. – TrevorLee Sep 3 '19 at 13:26
add a comment

2

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');
shareimprove this answerfollow
edited Oct 11 '17 at 10:45

Community♦
111 silver badge
answered Apr 2 '16 at 6:26

Abhigyan Singh
7599 bronze badges
add a comment

1

You can use an emulation of cls with for (int i = 0; i < 50; ++i) System.out.println();

shareimprove this answerfollow
answered Jan 10 '15 at 5:09

Epic
1051111 bronze badges
2
Its just a hint, maybe someone want to clear the screen, Actually – Sarz Jan 30 '15 at 10:48
@Sarz: and actually "clearing the screen" doesn't make proper sense by itself, either – Gyom Feb 6 '15 at 13:07
add a comment

-2

You need to use JNI.

First of all use create a .dll using visual studio, that call system("cls"). After that use JNI to use this DDL.

I found this article that is nice:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=5170&lngWId=2

shareimprove this answerfollow
answered Sep 30 '14 at 16:47

Denny
9777 bronze badges
That's work to me. I have a real project using JNI to clear the screen in JAVA. – Denny Apr 30 '15 at 14:36
add a comment
Highly active question. Earn 10 reputation in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
Not the answer you're looking for? Browse other questions tagged java console clear or ask your own question.

来源:互联网