Java如何获取文件的创建时间更新时间

Posted N!CE波

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java如何获取文件的创建时间更新时间相关的知识,希望对你有一定的参考价值。

一、通过下面方式

    BasicFileAttributes attr = null;
        try {
            Path path =  file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建时间
        Instant instant = attr.creationTime().toInstant();

 

二、完整代码

public class ReadFileTimeUtils {

    public static String file = "/Users/zhangboqing/Downloads/testfileclassify copy/Archives/2020-21-07/11.dmg";

    public static void main(String[] args) throws IOException {

        File f = new File(file);
        System.out.println(getCreationTime(f));
//        Path file =  f.toPath();
//        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
//        System.out.println("creationTime: " + attr.creationTime());
//        System.out.println("lastAccessTime: " + attr.lastAccessTime());
//        System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
    }


    public static String getCreationTime(File file) {
        if (file == null) {
            return null;
        }

        BasicFileAttributes attr = null;
        try {
            Path path =  file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建时间
        Instant instant = attr.creationTime().toInstant();
        // 更新时间
//        Instant instant = attr.lastModifiedTime().toInstant();
        // 上次访问时间
//        Instant instant = attr.lastAccessTime().toInstant();
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant);
        return format;
    }
}  

 

以上是关于Java如何获取文件的创建时间更新时间的主要内容,如果未能解决你的问题,请参考以下文章