Create file name using date and time

Tom picture Tom · Mar 9, 2011 · Viewed 88.2k times · Source

I hope you could help me, I'm trying to call in the date from another class and looks like "2011-03-09 06-57-40", I want to use this to create the file below but everytime I do when the output runs it creates a new file as it re-runs calling the dat(). I know what's going wrong I'm just not sure how to fix it, I want to permently writw to the same file. I hope this makes sense? :/

Thank you for any help in advance :)

    date d = new date();
    String  cdate = d.date();


    String f = h;

    try{
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(cdate + ".tsv", true)));
        out.print(f);
        out.print("\t");
        out.close();
    }catch (IOException e){
    }

Answer

Rune Aamodt picture Rune Aamodt · Mar 9, 2011

To create a file named the current date/time:

Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
File file = new File(dateFormat.format(date) + ".tsv") ;
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("Writing to file");
out.close();