Change last access time for a File in Java NIO Example

Java NIO - Change Last Access Time for File


In this NIO tutorial, we will explain how to change last access time for a file, using a Java program. We earlier discussed about changing created and modified time stamps for a file. This example is based on the previous series, and hope it will be a good learning on NIO library for you.

Input File

The test file we will use to change last access time stamp, is provided in the screen shot below:
Change Last Access Time for File - Java NIO - Input File
Change Last Access Time for File - Java NIO - Input File


Java NIO Program - Modify last accessed time


The Java program that changes the last accessed time stamp for a 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 ChangeLastAccessTime {
    public static void main(String[] args) throws Exception {
        /* Access the file first */
        Path path = Paths.get("C:", "test.wav");
        /* Get System time to set against created timestamp */
        long time = System.currentTimeMillis();
        /* Get FileTime value */
        FileTime fileTime = FileTime.fromMillis(time);
        /* Change Last Access time stamp value*/
        Files.setAttribute(path, "basic:lastAccessTime", fileTime, NOFOLLOW_LINKS);                             
    }
}
This program changes the last accessed time stamp for a file as expected. Refer to an example output screen below:

Java Program Output - Last Accessed time stamp changed
After change - modified last accessed timestamp value
That completes a quick tutorial to change last accessed time stamp for a file, using Java NIO. 

No comments:

Post a Comment