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 modified date in a FileTime
object.
Let’s try the code snippet below.
package org.kodejava.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() = 2021-05-05T17:09:09.0628061Z
lastModifiedTime() = 2021-11-04T00:11:43.279Z
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023