A program generates a file on a regular time schedule. We can use the current date and time as a filename. This avoids file system conflicts.
With a format string
, we create a filename String
. We specify that the year, month, day, hour, minute and second is present.
This program first calls Calendar.getInstance
to access a calendar. It then sets the time to the current instant—it uses the now()
method.
String.format
method with two arguments: a format string
, and the calendar containing the current date.string
.import java.time.Instant; import java.util.Calendar; import java.util.Date; public class Program { public static void main(String[] args) { // Get a Calendar and set it to the current time. Calendar cal = Calendar.getInstance(); cal.setTime(Date.from(Instant.now())); // Create a filename from a format string. // ... Apply date formatting codes. String result = String.format( "file-%1$tY-%1$tm-%1$td-%1$tk-%1$tS-%1$tp.txt", cal); // Display our result filename. System.out.println("Filename:"); System.out.println(result); } }Filename: file-2015-05-04-16-07-pm.txt
Program
resultThe program generated a string
with a filename that could be used to store time-sensitive information. It contains the date, month, year, hour, minute and seconds.
With the format string
in this example we can add six time fields to a filename in one line of code. The symbols are hard to read, but can be learned.
For log files, or files that are written on a timed basis, this approach to generating filenames is useful. It avoids conflicts which could caused at a loss.