Adding The Date and Time to the File name

37,880

Solution 1

If using java 8

DateTimeFormatter timeStampPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        System.out.println(timeStampPattern.format(java.time.LocalDateTime.now()));

Solution 2

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

Basically you are using outFile before its initialized.

Solution 3

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"))
    ...
Share:
37,880
Paul
Author by

Paul

Updated on June 05, 2020

Comments

  • Paul
    Paul about 4 years

    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"));
    
  • Paul
    Paul about 12 years
    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"));
  • Suraj Chandran
    Suraj Chandran about 12 years
    Try putting that line just after the date=new Date() statement
  • Basil Bourque
    Basil Bourque about 8 years
    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.