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
Latest posts by Wayan (see all)
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020