Java File setLastModified(long time) method with examples

April 28, 2020 No comments Java IO File Examples setLastModified

1. Introduction

The setLastModified(long time()) method sets the last modified time of the file or directory.

2. Method signature

public boolean setLastModified(long time)

Parameters:

  • time - the new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)

Returns

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

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. The code snippet that changes last-modified date of the file /tmp/exists.txt

package com.frontbackend.java.io;

import java.io.File;
import java.time.Instant;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File file = new File("/tmp/exists.txt");

            System.out.println(file.lastModified());

            boolean stat = file.setLastModified(Instant.parse("2020-01-30T18:35:24.00Z").toEpochMilli());
            if (stat) {
                System.out.println("File last-modified date changed successfully");
            }

            System.out.println(Instant.ofEpochMilli(file.lastModified()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

1588111090000
File last-modified date changed successfully
2020-01-30T18:35:24Z

4. Conclusion

In this article, we presented the method to change last-modified date of the given file in Java.

{{ message }}

{{ 'Comments are closed.' | trans }}