I can get the last accessed time by using the below code.
public Date getLastAccessTime(String filePath) throws IOException {
File f = new File(filePath);
BasicFileAttributes basicFileAttributes = Files.getFileAttributeView(
f.toPath(),
BasicFileAttributeView.class).readAttributes();
Date accessTime = new Date(basicFileAttributes.lastAccessTime().toMillis());
return accessTime;
}
But in my linux system, it's configured as "relatime" in /etc/fstab.
Is it necessary to enable "atime" in /etc/fstab to get exact Last Accessed Time?
Is it necessary to enable "atime" in /etc/fstab to get exact Last Accessed Time?
Short answer: Yes
On Linux the JDK uses the sys_stat64()
syscall to retrieve information about file. If the kernel does not update the st_atime
field when the file is accessed then Java can't have this information.
The default behavior of the Linux kernel regarding the st_atime updating policy has been changed by Linux 2.6.30. relatime
is now the default dehavior. It means that st_atime
is updated only when st_mtime
or st_ctime
is updated but not when the file is accessed. If you want the old behavior you can use strictatime
. See the mount man page for more information (search for atime
, noatime
, relatime
, strictatime
).