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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4363197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:33:14  来源:igfitidea点击:

Getting the last modified date of a file in Java

javafilebrowserdate

提问by Supuhstar

I'm making a basic file browser and want to get the last modified date of each file in a directory. How might I do this? I already have the name and type of each file (all stored in an array), but need the last modified date, too.

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

采纳答案by icyrock.com

As in the javadocs for java.io.File:

如在 javadocs 中的java.io.File

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

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

回答by ROMANIA_engineer

Since Java 7, you can use java.nio.file.Files.getLastModifiedTime(Path path):

从 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);
}

where printFileNamecan look like this:

哪里printFileName看起来像这样:

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

Output:

输出

10/06/2016 - 11:02:41