Change Date Created Time for File Using Java Program NIO Example

Change Created Time Stamp for a File using Java


This tutorial provides a Java example, that explains how to update the date created timestamp for a file using a Java program. By date created, we mean the following time stamp information:

Change Created Time Stamp for a File Using Java Program
Change Created Time Stamp for a File Using Java Program

Java NIO - Program - Example


Let us now write a program that changes the Created timestamp to a different date time value and inspect the output. The Java Program to change the created timestamp for any file 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 FileCreatedTime {
    public static void main(String[] args) throws Exception {
        /* Step  -1: Access the file in Path object */
        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 Created Time Stamp */
        Files.setAttribute(path, "basic:creationTime", fileTime, NOFOLLOW_LINKS);                               
    }
}

Change File TimeStamp - Output


This program changes the created timestamp of the file, which can be seen from the output screenshot below:

File Created Time Changed Through Java Program
File Created Time Changed Through Java Program
In summary, Java NIO offers a very clever method to change the file created time of any file in the OS. You can do this by invoking the "setAttribute" method of Files class and pass the required parameters, that will change the date created time of a file. In the next example, we will discuss how to change the last modified timestamp of a file using Java NIO.

1 comment: