在Java中获取文件的最后修改日期

39

我正在制作一个基本的文件浏览器,并希望获取目录中每个文件的最后修改日期。我应该如何做?我已经有了每个文件的名称和类型(都存储在一个数组中),但还需要最后修改日期。

3个回答

46

就像在java.io.File的Java文档中所述:

new File("/path/to/file").lastModified()


40

自Java 7开始,您可以使用java.nio.file.Files.getLastModifiedTime(Path path)方法:

Path path = Paths.get("C:\\1.txt");

FileTime fileTime;
try {
    fileTime = Files.getLastModifiedTime(path);
    printFileTime(fileTime);
} catch (IOException e) {
    System.err.println("Cannot get the last modified time - " + e);
}

其中printFileName可以是这样的:

private static void printFileTime(FileTime fileTime) {
    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
    System.out.println(dateFormat.format(fileTime.toMillis()));
}

输出:

10/06/2016 - 11:02:41

27
答案正确且解释得很好,但请不要教导年轻人使用已经过时且出了名的麻烦的 SimpleDateFormat 类。自从 Java 8 开始,可以使用 FileTime.toInstant() 方法将时间戳转换为 Instant 类型,然后再将其转换为 ZonedDateTime 类型,最后可以使用 DateTimeFormatter 进行格式化输出。 - Ole V.V.

0
你可以通过以下方式来实现结果:解释返回类型等。希望能对你有所帮助。
File file = new File("\home\noname\abc.txt");
String fileName = file.getAbsoluteFile().getName(); 
// gets you the filename: abc.txt
long fileLastModifiedDate = file.lastModified(); 
// returns last modified date in long format 
System.out.println(fileLastModifiedDate); 
// e.g. 1644199079746
Date date = new Date(fileLastModifiedDate); 
// create date object which accept long
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
// this is the format, you can change as you prefer: 2022-02-07 09:57:59
String myDate = simpleDateFormat.format(date); 
// accepts date and returns String value
System.out.println("Last Modified Date of the FileName:" + fileName + "\t" + myDate); 
// abc.txt and 2022-02-07 09:57:59

2
请不要教年轻人使用过时而且臭名昭著的 SimpleDateFormat 类。至少不要将其作为首选项。也不要没有任何保留地使用它。我们在 java.time, 现代 Java 日期和时间 API, 和它的 DateTimeFormatter 中有更好的选择。 - Ole V.V.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接