Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java set accessed date on file

Tags:

java

Is there a way in java to set the access time without setting the date modified time as well?

This will be in essence a touch -a command.

the setLastModified method in File updates both the access time as well as the date modified.

We are currently using java 6. Moving to 7 wouldn't be out of the question.

like image 449
Tom Hubbard Avatar asked Nov 03 '25 00:11

Tom Hubbard


2 Answers

You can use Files.setAttribute() from Java 7:

FileTime fileTime = FileTime.fromMillis(millis);
Files.setAttribute(path, "lastAccessTime", fileTime);

The string "lastAccessTime" can be found in the description of the BasicFileAttributeView, which also provides an alternative way to set this property (together with Files.getFileAttributeView()):

Files.getFileAttributeView(path, BasicFileAttributeView.class).setTimes(null, fileTime, null);

I'm not aware of any pure Java way that works in Java 6 or earlier.

like image 155
Joachim Sauer Avatar answered Nov 05 '25 14:11

Joachim Sauer


I guess opening an input stream on the file should modify its access time. But I don't know of any API to directly modify this attribute in Java 6.

like image 32
JB Nizet Avatar answered Nov 05 '25 14:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!