39

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.

Ky -
  • 30,724
  • 51
  • 192
  • 308

3 Answers3

46

As in the javadocs for java.io.File:

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

Ky -
  • 30,724
  • 51
  • 192
  • 308
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
40

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
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 27
    The answer is correct and well explained, but please don’t teach the young ones to use the long outmoded and notoriously troublesome `SimpleDateFormat` class. Instead, since Java 8, use `FileTime.toInstant()`, convert the `Instant` to `ZonedDateTime` and either just print it or format it using a `DateTimeFormatter`. – Ole V.V. Jan 29 '18 at 10:47
0

You could do the following to achieve the result: Explained the returns types etc. Hope it helps you.

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
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Dec 10 '22 at 12:01