Java - Get last modified date of a file

Posted on November 4, 2016


The lastModified() method of the java.io.File class returns the time of a file that was last modified. This method returns time in milliseconds (long value) and 0L if the file does not exist or an I/O error occurs.

Here is an example to demonstrate this.

LastModifiedFileExample.java

package com.boraji.tutorial.io;

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

/**
 * @author imssbora
 * LastModifiedFileExample.java
 * Nov 4, 2016
 */
public class LastModifiedFileExample {
	public static void main(String[] args) {
		File file=new File("file.txt");
		
		/*Check if file exists*/
		if(file.exists()){
			/*Get last modified date*/
			long milliseconds=file.lastModified();
			
			/*Convert milliseconds into readable date time format*/
			DateFormat format=new SimpleDateFormat("MMMM dd, yyyy hh:mm a");
			System.out.println("File modified date is : "+format.format(milliseconds));
			
		}else{
			System.out.println("File does not exist.");
		}
	}
}

Output

File modified date is : November 04, 2016 07:57 PM