How to update the date and time of a file using Java

The date and time properties of a file can be set using the setAttribute method of the Files object of the nio package.

Syntax:

java.nio.file.Files.setAttribute(file.toPath(), "creationTime", time);

This example loads a file using the File object. It formats the date and time using a SimpleDateFormat with the date pattern defined by the pattern String. Then the date is converted to a FileTime using the milliseconds value. The FileTime date is then set as attributes using the Path of the file. The last modified time, last access time and creation Time are set using their attribute name on the file.

Create the following java file:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.FileTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUpdateDate {

    public static void main(String[] argv) {

	File file = new File("V:/tmp/test.txt");

	try {
	    String pattern = "yyyy-MM-dd HH:mm:ss";
	    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
	    Date timeToSet = simpleDateFormat.parse( "2015-12-01 10:00:00" );

	    FileTime time = FileTime.fromMillis( timeToSet.getTime() );

	    Files.setAttribute(file.toPath(), "lastModifiedTime", time);
	    Files.setAttribute(file.toPath(), "lastAccessTime", time);
	    Files.setAttribute(file.toPath(), "creationTime", time);
	} catch (IOException e) {
	    e.printStackTrace();
	} catch (ParseException e) {
	    e.printStackTrace();
	}

    }

}

The FileTime object is created using the milliseconds from a Date object. It is the number of milliseconds since epoch, January 1st 1970 at Midnight GMT. The instance of this class a immutable or thread safe. Once it is created, or can not be modified by another thread. In order to set a differente value a new Object needs to be instanciated.

References:

FileTime
SimpleDateFormat
BasicFileAttributeView

Recent Comments