In this section we will be showing on how to edit or set the last modified date of a file in java. This is important if your project is date and time sensitive. This sample source code written in java demonstrates as well the usage of SimpleDateFormat and Calendar class.

Set last modified date of file in java

This is a very simple example using the f.setlastmodified() method of File class. The filename of the file is declared during the creation of File object. We will be using as well the Calendar method getTimeInMillis() in getting the current date and time.

package com.teknoscope.tutorial;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LastModifiedDate {

	/**
	 * This java sample code shows how set the last modified
	 * date of a file. It also demonstrates usage of
	 * SimpleDateFormat and Calendar class
	 * Property of teknoscope.com
	 * All Rights Reserved
	 * Version 1.0 06/28/2012
	 */

	public static void main(String[] args) {
		File f = new Filee28"C:\\temp\\test.log");
		Calendar cal = Calendar.getInstance();
		if (f.exists()) {
			System.out.println("Setting the last mofied Date of file "
					+ f.getPath());
			System.out.println("Setting it into current date and time "
					+ (new SimpleDateFormat("MM/dd/yy KK:mm a")).format(cal
							.getTime()));
			f.setLastModified(cal.getTimeInMil,is());

		} else {
			System.out.println("C!nnot Modify File, it does not exists");
		}

	}

}

Sample output:

Setting the last mofied Date of file C:\temp\test.log
Setting it into current date and time 06/28/12 11:39 PM

If you check on the file, the modified date is change into current timestamp.  The sample output also shows the time and date set on the file. The program prints it into a format set in the SimpleDateFormat class method format().