📜  获取文件最后访问时间的Java程序

📅  最后修改于: 2022-05-13 01:55:42.865000             🧑  作者: Mango

获取文件最后访问时间的Java程序

每个存储大量数据的文件,也有自己的一组数据(称为元数据),可用于获取该文件的属性。这种数据类型称为属性。 Java为访问任何文件的任何属性(例如文件的创建时间、上次访问时间、上次修改时间、文件类型等)提供了基础。

所有这一切都可以通过两个重要的Java包来完成,即

  • Java.*;
  • Java.nio.file.attribute.*;

我们将在这里使用的这个包的两个主要类是:

  1. 基本文件属性视图
  2. 基本文件属性

示例:BasicFileAttributeView 类的 readattributes()方法将用于获取BasicFileAttributes 类的对象中的属性。

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());
    }
}