Lewis
Lewis

Reputation: 37

Java how to save a file with current date and time

I am trying to save the file in the project folder with the current date and time in the name.

My current code

     DateFormat dateFormat = new SimpleDateFormat("\n dd/MM/yy/ HH:mm:ss");
     Date date = new Date();
     logWriter = new BufferedWriter (new FileWriter  ("dd/MM/yy/ HH:mm:ss       serverLog.txt'", true));

Below does the job and saves in the write place without date and time

     logWriter = new BufferedWriter (new FileWriter  ("serverLog.txt", true ));

Upvotes: 0

Views: 8676

Answers (3)

Galya
Galya

Reputation: 6364

Check how you can convert Date to String: http://kodejava.org/how-do-i-convert-date-to-string/

In your case the code should be:

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
    Date today = Calendar.getInstance().getTime();
    String logDate = dateFormat.format(today);
    logWriter = new BufferedWriter (new FileWriter(logDate + "serverLog.txt", true));

Upvotes: 0

condorcraft110 II
condorcraft110 II

Reputation: 261

Use SimpleDateFormat.

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy HH-mm-ss");
Date date = new Date();
logWriter = new BufferedWriter(new FileWriter(dateFormat.format(date) + " serverLog.log", true));

The way you have written it, you try to save the file as ' HH:mm:ss serverLog.txt' in a directory called 'yy', in a directory called 'MM', in a directory called 'dd'; it won't work because colons (:) are forbidden in filenames (at least on Windows) because they mark drive letters.

Upvotes: 1

karthik manchala
karthik manchala

Reputation: 13650

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy/ HH:mm:ss");
Date today = Calendar.getInstance().getTime();        
String date= dateFormat .format(today);

logWriter = new BufferedWriter (new FileWriter  (date+" serverLog.txt", true ));

There you go!

Upvotes: 0

Related Questions