Reputation: 927
I am trying to get the current time and append it to the name of a file that I generate.
the code snippet:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(app.values.getProperty("yyyy-MM-dd"));
LocalDateTime now = LocalDateTime.now();
String date = dtf.format(now);
Date today = Calendar.getInstance().getTime();
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");
This works fine on linux (returns "Receipt_2018-04-18_11:13" for the name of the file) but when I run the jar on windows 7, it only gives
Receipt_2018-04-18_11
and the generated file is damaged and empty. How can I fix this?
Upvotes: 0
Views: 794
Reputation: 347204
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");
:
is an illegal file character (under Windows at least, probably others).
For more information, have a look at Naming Files, Paths, and Namespaces, it contains a list of invalid file/directory name characters
Maybe change it to -
, for example
SimpleDateFormat timeFormat = new SimpleDateFormat("hh-mm");
String time = timeFormat.format(today);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + date + "_"+time+".pdf");
or use SimpleDateFormat timeFormat = new SimpleDateFormat("hhmm");
instead
So apparently fixing the immediate issue isn't enough for some people.
The java.util.Date
classes are generally considered deprecated and you should instead make use of the newer (and improved) java.time
API instead, for example...
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_hh-mm");
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + formatter.format(LocalDateTime.now()) + ".pdf");
Or, if you can't (use Java 8+), one of the many available libraries, including the back port for java.time
Upvotes: 1
Reputation: 45
Try this i think it will work with you
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date));
Upvotes: -1
Reputation: 1885
The issue is that ':' is incorrect character for the filenames on Windows OS, thus it needs to be replaced. Basically your code is excessive, you don't need Calendar
since LocalDateTime
already has timestamp part.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd_hh_mm");
LocalDateTime now = LocalDateTime.now();
String dateTime = dtf.format(now);
FileOutputStream fs = new FileOutputStream("receipt/Receipt_" + dateTime + ".pdf");
Hope it helps!
Upvotes: 3