Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 1.98 KB

89.md

File metadata and controls

51 lines (37 loc) · 1.98 KB

如何在 java 中获取文件的最后修改日期

原文: https://beginnersbook.com/2014/05/how-to-get-the-last-modified-date-of-a-file-in-java/

在这里,我们将学习如何在 java 中获取文件的最后修改日期。为了做到这一点,我们可以使用File类的lastModified()方法。以下是此方法的签名。

public long lastModified()

它返回上次修改此抽象路径名表示的文件的时间。此方法返回的值以毫秒为单位,因此为了使其可读,我们可以使用SimpleDateFormat格式化输出。

完整代码:

这里我们获取文件Myfile.txt的最后修改日期,该日期存在于驱动器C中。由于方法返回的值不可读,我们使用SimpleDateFormat类的format()方法对其进行格式化。

import java.io.File;
import java.text.SimpleDateFormat;
public class LastModifiedDateExample
{
    public static void main(String[] args)
    {	
        //Specify the file path and name
	File file = new File("C:\\Myfile.txt");
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	System.out.println("Last Modified Date: " + sdf.format(file.lastModified()));
    }
}

输出:

Last Modified Date: 01/03/2014 22:41:49

我们可以以任何所需的格式格式化和显示输出。例如,如果我们使用以下模式:

SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yy HH:mm a");
System.out.println("Last Modified Date: " + sdf2.format(file.lastModified()));

我们将获得以上输出以上模式:

Last Modified Date: 01-03-14 22:41 PM

您可以使用其他几种模式来获得所需形式的输出。要阅读有关日期格式的更多信息,请参阅SimpleDateFormat javadoc