2014-06-30 27 views
2

我正在嘗試編寫一個控制檯程序以在同一行和位置上遞歸顯示當前時間。使時間出現在同一位置的控制檯程序

我嘗試了很多,但它使用正常的System.out.println, ,因此我使用了printstream obj。現在的事情是,它出現在相同的位置,但沒有得到更新。

我無法確定問題是否出現在線程或printstream中。請幫助我解決這個問題,或者是否有任何其他方法讓事情在控制檯op中的相同位置遞歸顯示?

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); 

    } 
    }`` 
} 
+0

首先,使用Thread.start()而不是Thread.run()執行一個線程。 – Sanjeev

+0

是的,你正在寫Sanjeev調用Thread.run()會在同一個線程中執行run()方法,而無需啓動新線程。所以使用Thread.start()來代替。 –

回答

5

首先你的標題是誤導性的,請閱讀Recursion的含義。

你需要做的是用新時間覆蓋curret行。這是在控制檯程序中通過使用回車字符\r(回去一個字符,你可以使用退格字符\b

你可以嘗試這樣的事情(請注意,爲了這個工作,你不能打印在你行的末尾新行charachter \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); 
     } 
    } 
} 
0

如果使用的System.out.println您的問題()是它的印刷總是另一條線則只是嘗試是System.out.print使用()和印刷只是給它一個是System.out.print(後\ n)或system.print.out.println()

+0

實際上這個概念是打印在相同的位置上,而不是在同一行 – rrk

1

另一種方法是刪除當前行中的數字字符的((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); 
      } 
     } 
    } 
} 

但是,像A4L的答案,這在每個控制檯,例如Eclipse中都不起作用。

+0

+1中考慮要覆蓋的長度 – A4L

相關問題