2015-11-19 121 views
0

在控制檯中,在eclipse中彈出當前時間戳,並且我可以在它旁邊鍵入任何我想要放入文件的內容。將時間戳添加到文件JAVAR

如何獲得該文件中打印的時間戳!?!?

import java.io.BufferedWriter; 
    import java.io.File; 
    import java.io.FileWriter; 
    import java.io.IOException; 
    import java.util.Scanner; 
    import java.sql.Timestamp; 
    import java.util.Date; 
    public class bufferedwriter {  
    public static void main(String[] args) { 

     Scanner myScanner = new Scanner(System.in); 
     String lineToPrint = ""; 
     String fileName = "/Users/josephbosco/fileName.txt"; 

     do{ 
      java.util.Date date= new java.util.Date(); 
      System.out.print(new Timestamp(date.getTime())); 

      lineToPrint = myScanner.nextLine();     
      printToFile (fileName, lineToPrint);     

     } while (!lineToPrint.equalsIgnoreCase("q"));   

    } 

    public static void printToFile (String myfileName, String message) {   

     try { 
      File outfile = new File(myfileName); 

      //if file doesn't exist, then create it 

      if (!outfile.exists()) { 
       System.out.println("No file exists...writing a new file"); 
       outfile.createNewFile(); 

      } 
      FileWriter fw = new FileWriter(outfile.getAbsoluteFile(), true); 
      BufferedWriter bw = new BufferedWriter(fw); 
      bw.write(message); 

      bw.flush(); 
      bw.close(); 

      System.out.println("Done"); 

      } catch (IOException e) { 
       e.printStackTrace();      
     }  
    }  
} 

回答

0

您的代碼實例print語句中的新Timestamp對象。問題是您沒有將該時間戳存儲到變量,以便在嘗試將其寫入文件時可以再次引用該時間戳。

do{ 
    java.util.Date date= new java.util.Date(); 
    System.out.print(new Timestamp(date.getTime())); 


    lineToPrint = myScanner.nextLine(); 

    printToFile (fileName, lineToPrint); 


} while (!lineToPrint.equalsIgnoreCase("q")); 

將Timestamp對象存儲到變量允許您引用打印語句中的變量;這也使得時間戳變量和lineToPrint變量的連接更易於編碼。下面的修改代碼顯示了這些更改。

do{ 
    java.util.Date date= new java.util.Date(); 

    // Initialize variable and store new Timestamp object 
    Timestamp timestamp = new Timestamp(date.getTime())); 

    System.out.print(timestamp) 
    lineToPrint = myScanner.nextLine(); 

    // Concatenate the two variables 
    printToFile (fileName, timestamp + " " + lineToPrint); 


} while (!lineToPrint.equalsIgnoreCase("q")); 
0

每次調用bw.write(message);時間只需添加以下內容:目前

bw.write(new Timestamp(new java.util.Date().getTime()).toString()); 
+0

謝謝生病嘗試一下! – boejosco

+0

當我試圖說我在「寫」下發生錯誤時說 - 方法寫入(int)在BufferedWriter類型不適用於參數(時間戳) – boejosco

+0

嘗試使用'bw.write(new Timestamp(new java.util。 Date().getTime())。toString());' – jiaweizhang