Java File lastModified() Method
lastModified()In Java, this isjava.io.Filean instance method provided by the [File] class, used to retrieve the timestamp of the file's last modification. This method returns alongvalue of type, representing the number of milliseconds since January 1, 1970 00:00:00 GMT (i.e., the Unix epoch).
Method Syntax
Example
Return Value Description
- Return value type:
long - Return value meaning: the timestamp (in milliseconds) of the file's last modification
- Special return value: if the file does not exist or an I/O error occurs, returns
0L
Usage Example
Basic Usage
Example
public class LastModifiedExample {
public static void main(String[] args) {
File file = new File("example.txt");
long lastModified = file.lastModified();
System.out.println(File last modified timestamp: + lastModified);
}
}
Convert timestamp to readable format
Example
import java.text.SimpleDateFormat;
import java.util.Date;
public class LastModifiedReadable {
public static void main(String[] args) {
File file = new File("example.txt");
long lastModified = file.lastModified();
Date date = new Date(lastModified);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(File last modified time: + sdf.format(date));
}
}
Notes
File Does Not Exist: if the file does not exist, the method will return0L. Therefore, you should check whether the file exists before using it:
Example
long lastModified = file.lastModified();
// Handle the timestamp
} else {
System.out.println(File does not exist);
}
Permission Issues: if the program does not have permission to read the file's metadata, the method may also return0L。
Cross-platform Behavior: Different operating systems may have slightly different definitions of "last modified time", but it usually refers to the time when the file content was last modified.
Precision Issues: Some file systems may not accurately record millisecond-level timestamps.
Practical Application Scenarios
- File synchronization: compare the last modified times of two files to determine which file needs to be updated
- Cache mechanism: check whether a resource file has been modified to decide whether it needs to be reloaded
- Log analysis: analyze file modification time patterns to detect abnormal behavior
- Backup system: determine which files need to be backed up
Related Methods
File.setLastModified(long time): set the file's last modification timeFile.length(): get the file sizeFile.exists(): check whether the file exists
Summary
lastModified()The method is a simple but practical tool in Java file operations. It provides basic information about the file modification time. By combining theDateandSimpleDateFormatclass, we can convert these timestamps into a more readable format. In practical applications, making reasonable use of file modification time can implement many useful functions.
Java File