shank087 shank087 - 3 months ago 6
Java Question

Appending current date and time to XLSX file

Is there any issue with the below code? I am getting "java.io.FileNotFoundException:" exception. My requirement is to append the current system date and time to the xlsx file.

String date=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date());
FileOutputStream fileOut = new FileOutputStream("F:\\JobStatus_"+date+".xlsx");
workbook.write(fileOut);
fileOut.close();

Answer

Output of your current program will be

F:\\JobStatus_09/04/2016 09:10:34.xlsx

This will be your final output file path

when OS tries to find the path it will consider / as directories.

I suggest you to use _ for date saparator instead of /, space and :

use the following code

String date=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date());

date=date.replaceAll("/","_");
date=date.replaceAll(" ","_");
date=date.replaceAll(":","_");

 FileOutputStream fileOut = new FileOutputStream("F:\\JobStatus_"+date+".xlsx");
 workbook.write(fileOut);
 fileOut.close();