Getting the last modified date of a file in Java

前端 未结 2 549
北海茫月
北海茫月 2020-12-01 16:12

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

相关标签:
2条回答
  • 2020-12-01 16:52

    As in the javadocs for java.io.File:

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

    0 讨论(0)
  • 2020-12-01 16:53

    Since Java 7, you can use 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 printFileName can look like this:

    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
    
    0 讨论(0)
提交回复
热议问题