Set last modified date of a file in Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to set last modified date of a file in Java. java.io.File.setLastModified(long time) sets the last-modified time of the file or directory named by abstract pathname.

File.setLastModified() syntax

java.io.File.setLastModified(long time) sets the last-modified time of the file or directory named by abstract pathname. Refer below syntax

boolean java.io.File.setLastModified(long time);

Parameters - time the new last-modified time, which is measured in milliseconds.

Returns - true if and only if the operation succeeded; false otherwise

Throws - IllegalArgumentException - If the argument is negative. SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the named file

File.setLastModified() Example

In the following example, We will sets the last modified date of the jar file using java.io.File.setLastModified(long time) method.

package com.technicalkeeda.app;

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

public class SetLastModifiedDateExample {
    public static void main(String[] args) {

        File file = new File("C:\\demo\\file.jar");

        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");

        System.out.println("Last Modified Date (before):- " + sdf.format(file.lastModified()));

        file.setLastModified(new Date().getTime());

        System.out.println("Last Modified Date (after):- " + sdf.format(file.lastModified()));

    }
}

Output

Last Modified Date (before):- 11-03-2012 16:47:52
Last Modified Date (after):- 10-24-2016 09:42:07


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0348 seconds.