Get the Last Access Time for a File
Asked Answered
G

2

17

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?

Gave answered 28/5, 2009 at 10:53 Comment(2)
Bear 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.Bryant
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.Bostic
B
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.

Bostic answered 28/5, 2009 at 11:2 Comment(4)
i would like to know how java 7 gets the last accessed time.Edla
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.Bostic
BasicFileAttributes cannot be resolved. I am using Java 1.8. What could be wrong?Arnett
Does that mean the file has to be last opened in order for lastAccessTime to return correct value?Hypostyle
O
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.

Overheat answered 28/5, 2009 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.