How to get last Modified Date of Files

This is a basic example of how to get last modified date of a file in Java, using BasicFileAttributes class and file.lastModified().

  • First Example:
package com.nourit.javaIO;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class FileLastmodifiedDate {

  public static void main(String[] args) throws IOException {
      Path p = Paths.get("D:/tmp/nourit.txt");
      BasicFileAttributes view = Files.getFileAttributeView(p, BasicFileAttributeView.class).readAttributes();
      Date lastModifiedDate = new Date(view.lastModifiedTime().to(TimeUnit.MILLISECONDS));
      System.out.println("File " + p.toString() + " lastModified " + lastModifiedDate);
  }
}
  • Second Example:
package com.nourit.javaIO;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class FileLastmodifiedDate1 {

  public static void main(String[] args) {
    File file = new File("D:/tmp/nourit.txt");
    Path filePath = file.toPath();

    BasicFileAttributes attributes = null;
    try {
      attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
    } catch (IOException exception) {
      System.out.println(exception.getMessage());
    }
    Date lastModifiedDate = new Date(attributes.lastModifiedTime().to(TimeUnit.MILLISECONDS));

    System.out.println("File " + filePath.toString() + " lastModified " + lastModifiedDate);
  }
}
  • Third Example with file.lastModified()
package com.nourit.javaIO;

import java.io.File;
import java.util.Date;

public class FileLastmodifiedDate2 {

  public static void main(String[] args) {
    
    File file = new File("D:/tmp/nourit.txt");
    Date lastModifiedDate = new Date(file.lastModified());
    System.out.println("File " + file.getPath() + " lastModified " + lastModifiedDate);
  }
}

 

Output:

File D:\tmp\nourit.txt lastModified Thu Oct 12 16:03:27 CEST 2017

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*