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);
}
}
}
First your title is misleading, please read what Recursion means.
What you need to do is to override the curret line with the new time. This is done in a console programm by using the the carriage return charcter \r
(to go back one character you can use the backspace character \b
)
You could try something like this (Note that for this to work you must not print a new line charachter \n
at the end of your line ):
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);
}
}
}
Another way is to delete a number of chars from the current line ((char)8) :
public class Time {
public static void main(String... args) throws InterruptedException {
while (true) {
Date now = new Date();
System.out.print(now.toString());
Thread.sleep(1000);
for (int i = 0; i < now.toString().length(); i++) {
System.out.print((char) 8);
}
}
}
}
But like A4L's answer, this won't work in every console, i.e. Eclipse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With