我正在制作一个基本的文件浏览器,并希望获取目录中每个文件的最后修改日期。我应该如何做?我已经有了每个文件的名称和类型(都存储在一个数组中),但还需要最后修改日期。
自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
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
SimpleDateFormat
类。至少不要将其作为首选项。也不要没有任何保留地使用它。我们在 java.time
, 现代 Java 日期和时间 API, 和它的 DateTimeFormatter
中有更好的选择。 - Ole V.V.
SimpleDateFormat
类。自从 Java 8 开始,可以使用FileTime.toInstant()
方法将时间戳转换为Instant
类型,然后再将其转换为ZonedDateTime
类型,最后可以使用DateTimeFormatter
进行格式化输出。 - Ole V.V.