I'm trying to write a console program to display the current time recursively on the same line and position.
I tried a lot but it is getting printed in multiple line using normal System.out.println
, so I used PrintStream
object. Now the thing is that it is appearing in the same position, but not getting updated.
I couldn't be sure whether problem is with thread or PrintStream
. Please help me with this problem or is there any other method to make things appear recursively on the same position in a console app?
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);
}
}
}