Java program to get file creation, last access and last modification time

In this java program, we are going to learn how to access file’s last access time, creation time and last modified time using BasicFileAttributes class.
Submitted by IncludeHelp, on November 12, 2017

Given a file and we have to access its creation, last access and last modified time using Java program.

Following packages are using here, to implement this program,

  • java.nio.file.*
  • java.nio.file.attribute.*
  • java.util.Calendar;

Program to get file creation, last access and last modification time in java

import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Calendar;
import java.util.Scanner;

public class TimeAttributeOfFile {
  public static void main(String[] args) throws Exception {
    // create object of scanner.
    Scanner KB = new Scanner(System.in);

    // enter path here.
    System.out.print("Enter the file path : ");
    String A = KB.next();
    Path path = Paths.get(A);
    BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);

    BasicFileAttributes attributes = view.readAttributes();

    // calculate time of modification and creation.
    FileTime lastModifedTime = attributes.lastModifiedTime();
    FileTime createTime = attributes.creationTime();

    long currentTime = Calendar.getInstance().getTimeInMillis();
    FileTime lastAccessTime = FileTime.fromMillis(currentTime);

    view.setTimes(lastModifedTime, lastAccessTime, createTime);

    System.out.println("Creation time of file is : " + attributes.creationTime());
    System.out.println("Last modification time of file is : " + attributes.lastModifiedTime());
    System.out.println("Last access time of file is : " + attributes.lastAccessTime());
  }
}

Output

Enter the file path : E:/JAVA
Creation time of file is : 2017-10-10T06:03:22.695314Z
Last modification time of file is : 2017-11-04T06:09:35.778029Z
Last access time of file is : 2017-11-04T06:09:35.778029Z

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.