An example to get last access time of file in java

2020-07-16 12:08发布

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?

标签: java
3条回答
贼婆χ
2楼-- · 2020-07-16 12:51

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());

    }

}
查看更多
萌系小妹纸
3楼-- · 2020-07-16 12:58

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()); 
    } 
}
查看更多
太酷不给撩
4楼-- · 2020-07-16 13:00

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.

查看更多
登录 后发表回答