Friends please help. I know that using jdk1.7 we can get the last access time of file. Can anyone give an example with codes to get last access time of file?
Asked
Active
Viewed 8,024 times
5
-
1possible duplicate of [Getting the last access time for a file in Java](http://stackoverflow.com/questions/920259/getting-the-last-access-time-for-a-file-in-java) – Bombe Jan 31 '12 at 15:46
-
I've read the above mentioned post.But it did not consist of an example to do the same. – Rak Jan 31 '12 at 15:51
-
Or, for Windows OS, you can also use JNA to get the last accessed time information of a file via `GetFileInformationByHandle()` function. [Get unique file id in Windows with Java?](http://stackoverflow.com/questions/8309199/get-unique-file-id-in-windows-with-java) – ecle Jan 31 '12 at 15:57
-
1@Rak, have you tried this new thing? It’s called “programming.” – Bombe Jan 31 '12 at 16:10
3 Answers
12
Since you mentioned in your question using jdk1.7 , you should really look into the interface BasicFileAttributes on method lastAccessTime() . I'm not sure what is your real question but if you mean you want an example with codes on reading a file last access time using jdk7, take a look at below.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.Files;
/**
* compile using jdk1.7
*
*/
public class ReadFileLastAccess {
/**
* @param args
*/
public static void main(String[] args) throws Exception
{
Path file_dir = Paths.get("/home/user/");
Path file = file_dir.resolve("testfile.txt");
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("Last accessed at:" + attrs.lastAccessTime());
}
}

Jasonw
- 5,054
- 7
- 43
- 48
0
Here is a similar example using compiler version 1.7 (Java 7)
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
class E
{
public static void main(String[] args) throws Exception
{
// On Dos (Windows) File system path
Path p = Paths.get( "C:\\a\\b\\Log.txt");
BasicFileAttributes bfa = Files.readAttributes(p, BasicFileAttributes.class);
System.out.println(bfa.lastModifiedTime());
}
}
0
Here is a simple code snippet that return last access time:
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;
}
I have tested it on JDK 1.7.0 Developer Preview on MacOS X.

animuson
- 53,861
- 28
- 137
- 147

Maciej Matecki
- 11
- 3
-
i see that the method getFileAttributeView(f.toPath(), BasicFileAttributeView.class) asks for 3 parameters. why is this difference there ? – randeepsp Sep 03 '12 at 10:55
-