我正在尝试编写一个控制台程序来在同一行和位置上递归显示当前时间。
我尝试了很多,但使用普通 System.out.println
打印成多行,所以我用了 PrintStream
目的。现在的问题是它出现在相同的位置,但没有得到更新。
我无法确定是线程问题还是 PrintStream
.请帮我解决这个问题,或者有没有其他方法可以让事情在控制台应用程序的同一位置递归出现?
import java.util.Date;
import java.io.IOException;
import java.io.*;
public class DateDemo {
// boolean flag=true;
public static void main(String args[]) {
DisplayTime dt=new DisplayTime();
Thread thread1=new Thread(dt,"MyThread");
//thread1.start();
thread1.run();
}
}
class DisplayTime extends Thread {
public void run() {
try {
while(true){
showTime();
Thread.sleep(1000);
}
} catch(InterruptedException e){
System.err.println(e);
}
}
public void showTime(){
try {
PrintStream original = new PrintStream(System.out);
// replace the System.out, here I redirect to
System.setOut(new PrintStream(new FileOutputStream("stdout.log")));
// System.out.println("bar"); // no output
Date date =new Date();
original.print(date.toString());
// System.out.println(date.toString());
System.out.flush();
// output to stdout
// original.close();
} catch(Exception e){
System.err.println(e);
}
}
}
最佳答案
首先你的标题有误导性,请阅读 Recursion方法。
您需要做的是用新时间覆盖当前行。这是通过使用回车符 \r
在控制台程序中完成的。 (要返回一个字符,您可以使用退格字符 \b
)
您可以尝试这样的操作(请注意,要使其正常工作,您不得在行尾打印新行字符 \n
):
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time {
public static void main(String... args) throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
while(true) {
System.out.printf("\r%s", sdf.format(new Date()));
Thread.sleep(1000);
}
}
}
关于java - 使时间出现在同一位置的控制台程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24487928/