Java File Last Modified Sample Code

The Java code below is a sample on how to retrieve the last time a file was modified, which means the last time the file was saved or created. Viewing a file and not saving it will not change the modified time. The Java File class contains a method called lastModified() method that returns a long that represent the last modified time.

If you look at the details of the lastModified() method, it states the long represents the number of milliseconds since the epoch the file was last modified. So what is this epoch? Basically it was a date set in time by some progrmamers, depending on the system you are on is around January 1, 1970.

Java Class: File
Method Name: lastModified()
Parameters: none
Return Type: long
Exceptions: SecurityException

Java File Last Modified Source Code:

package com.jcd.java.tutorials;

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

public class JavaLastModTime 
{

	public static void main(String[] args) 
	{
		String sampleFile;
		String lastModTime;
		File file;
			
		//Define a filename to look at that exists
		sampleFile = "C:\\Users\\Admin\\Documents\\JavaFile.txt";		
		
		//Create a File object
		file = new File(sampleFile);
		
		//Call method to get last modified time
		lastModTime = getLastModTime(file);
		
		System.out.println("\n"+file.getName()+" Last Modified On: "+lastModTime);
		
		//Define a filename to look at that does NOT exists
		sampleFile = "C:\\Users\\Admin\\Documents\\JavaFileXXX.txt";
		
		//Create a File object
		file = new File(sampleFile);
		
		//Call method to get last modified time
		lastModTime = getLastModTime(file);
		
		System.out.println("\n"+file.getName()+" Last Modified On: "+lastModTime);

	}
	
	public static String getLastModTime(File file) 
	{
		//Get the last modified time as a long since epoch
		long lastModTime = file.lastModified();
		
		//Create SimpleDateFormat object to show time as a readable string
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		
		//Format the time into a string
		String timeFormat = sdf.format(lastModTime);
		
		return timeFormat;
	}

}


Looking at the sample output below, you will see the last modified time of JavFileXXX.txt is December 31, 1969. Since this file does not exist in my environment, the lastModified() method will return the epoch time for it. You should first check if the File Exists before checking the last modified time.

Java File Exist Sample Output:


JavaFile.txt Last Modified On: 01/09/2018 05:14:38

JavaFileXXX.txt Last Modified On: 12/31/1969 19:00:00



References:

Add a Comment

Your email address will not be published. Required fields are marked *