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.io;
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() = 2017-11-28T00:08:55.291206Z lastModifiedTime() = 2017-12-01T14:56:21.26Z
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I clear the current command line in terminal? - February 14, 2019
- How do I generate random alphanumeric strings? - February 7, 2019
- Why do I get ArrayIndexOutOfBoundsException in Java? - January 29, 2019