Reputation: 351
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?
Upvotes: 5
Views: 8044
Reputation:
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());
}
}
Upvotes: 0
Reputation: 5064
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());
}
}
Upvotes: 12
Reputation: 11
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.
Upvotes: 0