Monday, 26 October 2015

How to find last modified date of a file - Java Program

In Java, there are two ways to get the last modified date of the file. If you are using version of Java less than 7 then you can use the File.lastModified() method to get the file's last modified timestamp.

If you are using Java 7 or above then you can also use java.nio BasicFileAttributes to get all the attributes associated with the file. That way apart from last modified date you can also get the file creation date and several other attributes.

public class FileDate {
    public static void main(String[] args) {
        /*For below Java 7*/ 
        // get the file
        File f = new File("F:\\NetJS\\programs.txt");
        // Create a date format
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        // get the last modified date and format it to the defined format
        System.out.println("File last modified date " + sdf.format(f.lastModified()));
        
        /*Java 7 or above using NIO*/
        // Get the file
        Path path = Paths.get("F:\\NetJS\\programs.txt");
        BasicFileAttributes attr;
        try {
            // read file's attribute as a bulk operation
            attr = Files.readAttributes(path, BasicFileAttributes.class);
            // File creation time
            System.out.println("File creation time - " + sdf.format(attr.creationTime().toMillis()));
            // File last modified date
            System.out.println("File modified time - " + sdf.format(attr.lastModifiedTime().toMillis()));
            
        } catch (IOException e ) {
            System.out.println("Error while reading file attributes " + e.getMessage());
        }
        
    }
}

Note here that when java.io.File lastModified method is used it returns the time in milliseconds (long) so SimpleDateFormat is used to format it into dd/MM/yyyy format.
Same way in the java.nio when attributes of the file are read, both file creation date and last modified date are displayed. Again the returned date is converted to milliseconds and then formatted to the desired format.

That's all for this topic How to find last modified date of a file. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to format date in Java using SimpleDateFormat
  2. How to read file from the last line in Java
  3. How to read input from console in Java?
  4. Reading file in Java using Scanner
  5. Reading file in Java using BufferedReader

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment