将时间戳添加到文件JAVA

时间:2015-11-19 04:26:12

标签: java printing timestamp filenames

在控制台中,在eclipse中,当前的时间戳会弹出,我可以在它旁边键入,无论我想将其放入文件中。

如何在文件中打印时间戳!?!?

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

2 个答案:

答案 0 :(得分:0)

每次致电registerUserNotificationSettings(settings)时,只需添加以下内容:

didFinishLaunchingWithOptions:

答案 1 :(得分:0)

您的代码当前正在print语句中实例化一个新的Timestamp对象。问题是您没有将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对象存储到变量允许您在print语句中引用该变量;这也使得时间戳变量和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") );