如何在java中查找文件的上次访问时间?

时间:2014-04-16 05:45:11

标签: java

我正在使用javxt.io.file库来检索特定文件的lastAccesstime但是我得到了相同的结果,即使它被多次访问。请让我知道我是否在做任何错误?

public class LastAccessTime 
{
     public static void main(String[] args) {
            javaxt.io.File file = new javaxt.io.File("C:/Users/IISU24/Desktop/calculator/rahul.txt");
            System.out.println("Accessed: " + file.getLastAccessTime());
     }
}

3 个答案:

答案 0 :(得分:3)

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.Files;

public class ReadFileLastAccess {
    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());
    }
}

答案 1 :(得分:1)

你不能用File做,尝试Java 7 NIO2

FileTime attr = (FileTime) Files.getAttribute(Paths.get("1.txt"), "lastAccessTime");

答案 2 :(得分:0)

NIO包是你的朋友:)

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

public class Snippet {

    public static void main(String[] args) throws IOException {
        Path file = Paths.get("target.target");
        BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("Last access time:" + attrs.lastAccessTime());
    }
}