How to find last modified time of a file in Java?

To answer this question, it is very easy to find the last modified timestamp of a file in Java using NIO. An example code, that helps to find the last modified time of 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.BasicFileAttributes;

public class LastModifiedTime {
    public static void main(String[] args) throws Exception {
        /* Step  -1: Access the file in Path object */
        Path path = Paths.get("C:", "test.xml");
        /* use readAttributes to read file attributes */
        BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
        /* Print File Creation Time Stamp */            
        System.out.println("File Modified TimeStamp: " + attributes.lastModifiedTime());                        
    }
}
At runtime, if the file cannot be found due to some reason, you will get NoSuchFileException. A sample exception is shown below:

Exception in thread "main" java.nio.file.NoSuchFileException: C:\test.xml
        at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
        at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
        at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
        at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Source)
        at sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(Unknown Source)
        at sun.nio.fs.WindowsFileSystemProvider.readAttributes(Unknown Source)
        at java.nio.file.Files.readAttributes(Unknown Source)
        at LastModifiedTime.main(LastModifiedTime.java:12)

If the file can be found, then Java returns the last modified timestamp of the file. An example output of a successful response is provided below:

File Modified TimeStamp: 2012-11-29T08:10:38.59375Z

Note that the method lastModifiedTime, can be used across all operating systems. Further, it returns the response as an object of type java.nio.file.attribute.FileTime, which you can use for further manipulation if required.

No comments:

Post a Comment