Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to get the last modified time of a file in Java

Programming Bytes

To get the Last Modified Time of a file, we can use the lastModified method of the File class present in the java.io package.

Syntax

public long lastModified()

Parameters

This method doesn’t take any argument.

Return value

This method returns the last modified time as a long value.

Code example

The below code demonstrates how to use the lastModified method to get the last modified time of a file.

main.java
test.txt
import java.io.File;
import java.util.Date;

class FileLastModifiedTime {
  public static void main(String[] args) {
    // File path
    String filePath = "test.txt";
    // create a File object 
    File file = new File(filePath);
    // get lastModified time 
    Long lastModified = file.lastModified();
    System.out.println("Last modifiedTime is: " + new Date(lastModified));
  }
}
Get last modified time of a file

Explanation

In the above code:

  • In lines 1 and 2: Imported the Files and Date classes.

  • In line 7: Created a String variable holding the path of the file as value (we have a test.txt file present in the same folder in which the program is executing).

  • In line 9: We have created a File object for the filePath.

  • In line 11:*Used the lastModified method to get the last modified time of the file. This will return the time in milliseconds.

  • In line 12: Created a new Date object from the last modified time of the file and printed it.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring