Change Last Modified Time in Java
In this tutorial, we will explain how easy it is to use NIO to change last modified time information against a File in Java. We had explained earlier how to modify the date created timestamp using Java. This example can be considered as an extension of that.
Current Modified TimeStamp - Input
We will use the following input file and check the file back after changing the time. A screendump of the file is given below:
Update Modified Time Stamp for a File Using Java |
Java Program - Example
The Java program that you can use to change the file modified time, is provided below:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
public class ChangeModifiedTime {
public static void main(String[] args) throws Exception {
/* Access the file first */
Path path = Paths.get("C:", "test.xml");
/* Get System time to set against created timestamp */
long time = System.currentTimeMillis();
/* Get FileTime value */
FileTime fileTime = FileTime.fromMillis(time);
/* Change File Modified time stamp value*/
Files.setAttribute(path, "basic:lastModifiedTime", fileTime, NOFOLLOW_LINKS);
}
}
This program uses Java NIO library, to modify the last updated time stamp value. The same file attributes after running this program is provided below:
Update Modified time stamp in Java - Output Screenshot |
This example can be used in any OS, and can be very handy in situations where you need to change modified time property for a file in the file system. Try this example, and post a comment if something is not working. We will provide another Java NIO example soon, that will explain how to change file accessed time stamp information. Stay connected.
No comments:
Post a Comment