How do I set file last modified time?

In the following code snippet you will learn how to update file’s last modified date/time. To update the last modified date/time you can use the java.nio.file.Files.setLastModifiedTime() method. This method takes two arguments. The first arguments is a Path object that represent a file. And the second arguments is the new modified date in a FileTime object.

Let’s try the code snippet below.

package org.kodejava.example.nio;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class SettingFileTimeStamps {
    public static void main(String[] args) throws Exception {
        String path = "D:\resources\data.txt";
        Path file = Paths.get(path);

        BasicFileAttributes attr =
                Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());

        //
        // Update the last modified time of the file.
        //
        long currentTimeMillis = System.currentTimeMillis();
        FileTime fileTime = FileTime.fromMillis(currentTimeMillis);
        Files.setLastModifiedTime(file, fileTime);

        attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());
    }
}

The output of the code snippet:

lastModifiedTime() = 2012-11-28T00:08:55.291206Z
lastModifiedTime() = 2012-12-01T14:56:21.26Z

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply