Maruthi Srinivas Sikhakolli Maruthi Srinivas Sikhakolli - 2 months ago 6
Java Question

Name a file in Java to include date and time stamp

I am exporting data into a file in a Java application using NetBeans. The file will have a hard coded name given by me in the code. Please find below the code.

private static String FILE = "D:\\Report.pdf";


I want to append date and time stamp to the file name generated so that each file created is a unique file. How to achieve this?

Answer

Use SimpleDateFormat and split to keep file extension:

private static String FILE = "D:\Report.pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE.split(".")[0] + df.format(new Date()) + FILE.split(".")[1];
// filename = "D:\Report20150915152301.pdf"

UPDATE:
if you are able to modify FILE variable, my suggestion will be:

private static String FILE_PATH = "D:\Report";
private static String FILE_EXTENSION = ".pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
// filename = "D:\Report20150915152301.pdf"
Comments