How to Set File Last Modified Date in Java


In this example we will show the method to change the file last modified date in Java.

Source Code

package com.beginner.examples;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileOperator16Example { 
	public static void main(String[] args ) throws ParseException
    {	
		try
        {
        	 File file = new File("example.txt");
        	 if (!file.exists()) 
        	 {
        		 file.createNewFile();
        	 }
        	 
        	 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        	 System.out.println("Last modified date is: " + df.format(file.lastModified()));
        	 
			 String date = "2019-03-02";
			 Date newDate = df.parse(date);
			 file.setLastModified(newDate.getTime());
			 System.out.println("Last modified date is: "+ df.format(file.lastModified()));
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Last modified date is: 2019-03-01
Last modified date is: 2019-03-02

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments