Skip to content
Related Articles

Related Articles

Java Program to Get the Last Access Time of a File
  • Last Updated : 07 Jan, 2021

Every file which stores a lot of data, also has its own set of data ( known as metadata) which can be used to get the properties of that file. Such data types are called attributes. Java provides a basis for accessing any attributes of any file such as creation time of the file, last access time, last modified time, type of file, etc.

All this can be done by two important packages of java i.e. 

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

The two main classes of this package which we will be using here are:

  1. BasicFileAttributeView
  2. BasicFileAttributes

Example: readattributes() method of BasicFileAttributeView class will be used to get the attributes in the object of BasicFileAttributes class.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to get the last access time of a file
  
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;
  
// save as file named gfg.java
public class gfg {
    public static void main(String[] args) throws Exception
    {
  
        // reading the file path from the system.
        Scanner sc = new Scanner(System.in);
  
        System.out.println("Enter the file path");
  
        String s = sc.next();
  
        // setting the path .
        Path path = FileSystems.getDefault().getPath(s);
  
        // setting all the file data to the attributes in
        // class file of BasicFileAttributeView.
        BasicFileAttributeView view = Files.getFileAttributeView(
                path, BasicFileAttributeView.class);
  
        // method to read the file attributes.
        BasicFileAttributes attribute = view.readAttributes();
  
        // using lastAccessTime() method to print the last
        // access time of that file.
        System.out.println("last access time is :"
                           + attribute.lastAccessTime());
    }
}

chevron_right



Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :