I know that using File
object we can get the last modified time for a File
(i.e. File.lastModified()). But, my requirement is to get the last accessed time for a File
in Java. How do I get it?
Asked
Active
Viewed 1.7k times
16
-
3Bear in mind that this information isn't reliable. People (myself included) typically turn off atime as it greatly speeds up disk access. People do it on servers too. – cletus May 28 '09 at 11:20
-
I'll second cletus. I turned atime on my WinXP off when I bought a SSD drive. That SSD wasn't good with random writes, and updating the last access times was killing my machine on otherwise read-only operations. – Esko Luontola May 28 '09 at 22:34
2 Answers
19
You will need to use the new file I/O API (NIO2) which comes with Java 7. It has a method lastAccessTime() for reading the last access time.
Here is a usage example:
Path file = ...
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
FileTime time = attrs.lastAccessTime();
For more information see Managing Metadata in the Java Tutorial.

Esko Luontola
- 73,184
- 17
- 117
- 128
-
-
Java 7 asks for it from the operating system, using some OS specific function. Is that what you wanted to ask? I've added an example of how Java 7 can be *used* to get the time, in case you meant instead that. – Esko Luontola Sep 04 '12 at 08:21
-
BasicFileAttributes cannot be resolved. I am using Java 1.8. What could be wrong? – Kala J Sep 17 '14 at 18:44
-
Does that mean the file has to be last opened in order for **lastAccessTime** to return correct value? – IgorGanapolsky Jun 12 '18 at 15:14
4
You can't do it with plain Java, you'll need to use JNI to access the platform specific data such as this or use extensions to the core Java library like the following:
javaxt.io.File file = new javaxt.io.File("path");
file.getLastAccessTime();
Or, if you have Java 7, go with Esko's answer and use NIO.

Kris
- 14,426
- 7
- 55
- 65