2015-11-19 92 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