【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; } }
你投入得越多,就能得到越多得价值