Change Last Modified Time of a File In Java

Category: Java   Tags: Java, Java File Handling, Java Path, Java NIO File System

To read the basic attributes of a file, you can use one of the Files.readAttributes methods. Here is one Java program for this:

JavaChangeLastModifiedFileTimeExample.java

                                package com.tutorial.java.files;

                                import java.io.IOException;
                                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 JavaChangeLastModifiedFileTimeExample {

                                    public static void main(String[] args) throws IOException {
                                        Path file = Paths.get("/home/manish/Desktop/sample.txt");
                                        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
                                        System.out.println("Last Modified Time before: " + attr.lastModifiedTime());

                                        long currentTime = System.currentTimeMillis();
                                        FileTime ft = FileTime.fromMillis(currentTime);
                                        Files.setLastModifiedTime(file, ft);
                                        attr = Files.readAttributes(file, BasicFileAttributes.class);

                                        System.out.println("Last Modified Time after: " + attr.lastModifiedTime());
                                    }
                                }
                            

Output:

                            Last Modified Time before: 2017-10-28T10:25:36Z
                            Last Modified Time after: 2017-10-28T10:53:10Z