我正在编写一个运行implements runnable
类的程序。
我有它所以格式为HH:MM:SS
的时间每秒都会打印到屏幕上。
下面是代码:
public class LaunchCounter
{
public static void main(String[] args)
{
//Runs the CounterThread
new CounterThread().start();
}
}
这是反击班
public class CounterThread implements Runnable
{
//Declare new thread
private Thread thread;
public void start()
{
thread = new Thread(this, "");
thread.start();
}
@Override
public void run()
{
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for(int i = 1; i > 0; i++)
{
try
{
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
catch(Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
这完全没问题。
我想要实现的是在等待一秒后清除打印的行,并打印新的时间,依此类推。
因此,12:00:01
取消了12:00:02
,而取了新的一行。
我已尝试System.out.print("\b\b\b\b\b\b\b")
和Runtime.getRuntime().exec( "cmd /c cls" );
但这只是在控制台上打印方块。
我将如何实现这一目标?
答案 0 :(得分:2)
问题是您正在使用的终端。 (我的猜测是你在IDE中使用终端。)如果输出终端没有进行完整的终端仿真,它将忽略\ b字符或将它们显示为不可打印的字符。
我在IntelliJ IDEA 16中测试了以下代码,并验证了内置IDEA终端忽略了\ b。然后我在MacOS终端上测试它,它按照你想要的方式工作。
package test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CounterThread implements Runnable {
//Declare new thread
private Thread thread;
public void start() {
thread = new Thread(this, "");
thread.start();
}
@Override
public void run() {
//Formatter used to display just time not date
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//never ending forloop to display time
for (int i = 1; i > 0; i++) {
try {
//Runtime.getRuntime().exec( "cmd /c cls" );
//Sleep for 1 second after each loop
Thread.sleep(1000);
//new calender is created
Calendar cal = Calendar.getInstance();
System.out.print("\b\b\b\b\b\b\b\b");
System.out.print(dateFormat.format(cal.getTime()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws Exception {
//Runs the CounterThread
new CounterThread().start();
final Object monitor = new Object();
synchronized (monitor) {
monitor.wait();
}
}
}
答案 1 :(得分:0)
您使用Runtime.getRuntime().exec("cls");
走在正确的轨道上。请参阅Holger的this帖子,了解为什么您无法清除控制台。
要解决此问题,我们必须调用命令行解释器 (cmd)并告诉它执行一个允许调用的命令(/ c cls) 内置命令。此外,我们必须直接连接其输出 通道到Java进程的输出通道,它起作用 Java 7,使用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(); } }
现在当Java进程连接到控制台时,即已经 从没有输出重定向的命令行开始,它将清除 控制台。