Home  >  Article  >  Java  >  How to get the last modified date of a file in java? (code example)

How to get the last modified date of a file in java? (code example)

青灯夜游
青灯夜游Original
2019-03-18 14:46:064649browse

如何在java中获取文件的最后修改日期?我们可以使用File类的lastModified()方法来获取。下面本篇文章就来带大家了解一下lastModified()方法的使用,希望对大家有所帮助。

How to get the last modified date of a file in java? (code example)

File类的lastModified()方法

lastModified()方法可以用于返回文件最后一次被修改的时间。

基本语法:

public long lastModified()

返回值:lastModified()方法返回由这个抽象路径名表示的文件上次被修改的时间;返回值以毫秒为单位,因此为了使其可读,我们可以使用simpledateformat格式化输出。

如何获取文件的最后修改日期?

下面通过代码示例来看看如何使用lastModified()方法获取件的最后修改日期。

示例:

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("D:\\Myfile.txt");
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("最后修改日期为:" + sdf.format(file.lastModified()));
    }
}

输出:

最后修改日期为:03/18/2019 10:41:49

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

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

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

最后修改日期为:03-18-19 10:41 AM

相关视频教程推荐:《Java教程

以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注php中文网相关教程栏目!!!

The above is the detailed content of How to get the last modified date of a file in java? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn