Adding The Date and Time to the File name
Asked Answered
H

9

6

Hello I am trying to add the date and time to a file name in JAVA. I can get the date and time printed within the file, which I also want done, but when I place the toString in the FileWriter I get a Null Pointer.

package com.mkyong;
import java.util.*;
import java.io.*;
import java.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

    public class Simplex {

        private static PrintWriter outFile;

        //Main Method
        public static void main(String[] args) throws IOException {



            // Instantiate a Date object
             Date date = new Date();

             // display time and date using toString()
             outFile.println(date.toString());
             outFile.println();
            //creates the new file to be saved


            outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + ".txt"));
Hicks answered 18/6, 2012 at 17:39 Comment(0)
P
10

If using java 8

DateTimeFormatter timeStampPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        System.out.println(timeStampPattern.format(java.time.LocalDateTime.now()));
Pacifist answered 18/4, 2016 at 7:57 Comment(1)
I suggest always passing a ZoneId object to the now() method. If omitted, the JVM‘s current default time zone is applied. That default can vary. Better to specify explicitly the expected/desired zone.Aglet
A
6

The line outFile = new PrintWriter(..) should occur before first usage of outFile.

Basically you are using outFile before its initialized.

Affection answered 18/6, 2012 at 17:42 Comment(2)
Ah Thank you. But when I reorder it, the compiler still does not like this line: outFile = new PrintWriter(new FileWriter("simplex" +(date.toString()) + ".txt"));Hicks
Try putting that line just after the date=new Date() statementAffection
M
5

I'd suggest you to use YYYY-MM-dd_hh-mm-ss formatting pattern in file name that allows you to sort out files in a more convinient way. Take a look at SimpleDateFormat class.

    ...
    Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
    outFile = new PrintWriter(new FileWriter("simplex_" + formatter.format(date) + ".txt"))
    ...
Missend answered 18/6, 2012 at 17:47 Comment(1)
Using SimpeDateFormat and Date was OK in 2012, but they have been outdated for 10 years now and are not recommended. Use java.time, the modern Java date and time API, as shown in some other answers. Also your format pattern is wrong will give wrong date/time around midnight, in the afternoon and around New Year.Wyler
S
2
LocalDateTime current = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");
String formatedDateTime = current.format(format);
outFile = new PrintWriter(new FileWriter("simplex" + formatedDateTime  + ".txt"));
Succinctorium answered 20/4, 2022 at 12:36 Comment(0)
J
1

The below method will be useful generate filename with date time using LocalDateTime using Java 8+

private String getFileName(String fileName) {
    LocalDateTime current = LocalDateTime.now();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("ddMMyyyyHHmmss");
    String name = fileName.substring(0,fileName.lastIndexOf("."));
    String ext = fileName.substring(fileName.lastIndexOf("."));
    return name+"_"+current.format(format)+ext;
}
Jonquil answered 26/6 at 19:59 Comment(1)
Thanks for suggesting java.time, it’s a good idea. I recommend passing time zone to LocalDateTime.now(), for example LocalDateTime.now(ZoneId.systemDefault()). You may also use ZonedDateTime instead.Wyler
V
0
// display time and date using toString()
outFile.println(date.toString());

With the code, You use outFile before initialize it.

Vickery answered 18/6, 2012 at 17:44 Comment(1)
Correct. The problem is treated in more depth in the answer by Suraj Chandran and the comments under it.Wyler
B
0

Just save it in a variable. You should use the new Date(long) constructor, btw.

public class Simplex {

    private static PrintWriter outFile;

    //Main Method
    public static void main(String[] args) throws IOException {



        // Instantiate a Date object
         Date date = new Date(System.currentTimeMillis());
         String dateString = date.toString();


        outFile = new PrintWriter(new FileWriter("simplex" + dateString + ".txt"));


         outFile.println(dateString);
         outFile.println();
        //creates the new file to be saved
Ballarat answered 18/6, 2012 at 17:46 Comment(0)
M
0

Problem is that outFile is declared as a static, but never initialized until after you already used it.

You need to first initialize/instantiate outFile first before actually using it:

 private static PrintWriter outFile;

    //Main Method
    public static void main(String[] args) throws IOException {

        // Instantiate a Date object
         Date date = new Date();

        //creates the new file to be saved
        outFile = new PrintWriter(new FileWriter("simplex" + (date.toString()) + .txt"));
        // display time and date using toString()
         outFile.println(date.toString());
         outFile.println();

Although I'm not entirely sure why you are even creating outFile as a static object, and not just a local variable.

Mitten answered 18/6, 2012 at 17:47 Comment(0)
B
0

The below mentioned snippet can be used

 String logFileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

 logFileName = "loggerFile_" + logFileName;
Benitez answered 5/6, 2017 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.