Write a java program to get file creation, last access and last modification time


The Time_AttributeFile class uses the java.nio.file package to obtain the file attributes of a specified file path. The lastModifiedTime() and creationTime() methods of the BasicFileAttributes class are used to obtain the last modification and creation times of the file, respectively.

The Calendar class is used to obtain the current time in milliseconds, which is then converted to a FileTime object using the fromMillis() method. The setTimes() method of the BasicFileAttributeView class is then used to set the new last modification and last access times, as well as the original creation time of the file.

Finally, the new file attributes are printed using the creationTime(), lastModifiedTime(), and lastAccessTime() methods of the BasicFileAttributes class.

Note that modifying file attributes can have implications on the system and may require appropriate permissions

Source Code

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Calendar;
import java.util.Scanner;
public class Time_AttributeFile
{
	public static void main(String[] args) throws Exception
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter the File Path : ");
		String f = input.next();
		Path file_path = Paths.get(f);
		BasicFileAttributeView view = Files.getFileAttributeView(file_path, BasicFileAttributeView.class);
 
		BasicFileAttributes attr = view.readAttributes();
 
		// calculate time of modification and creation.
		FileTime lastmodifedtime = attr.lastModifiedTime();
		FileTime cre_time = attr.creationTime();
 
		long cur_time = Calendar.getInstance().getTimeInMillis();
		FileTime lastaccesstime = FileTime.fromMillis(cur_time);
 
		view.setTimes(lastmodifedtime, lastaccesstime, cre_time);
 
		System.out.println("Creation Time of File : " + attr.creationTime());
		System.out.println("Last Modification Time of File : " + attr.lastModifiedTime());
		System.out.println("Last Access Time of File : " + attr.lastAccessTime());
	}
}

Output