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:
- BasicFileAttributeView
- BasicFileAttributes
Example: readattributes() method of BasicFileAttributeView class will be used to get the attributes in the object of BasicFileAttributes class.
Java
// 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()); } } |