📜  获取基本文件属性的Java程序

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

获取基本文件属性的Java程序

基本文件属性是与文件系统中的文件相关联的属性,这些属性是许多文件系统共有的。为了获得基本的文件属性,我们必须使用 BasicFileAttributes 接口。这个接口是 2007 年引入的,是 nio 包的一部分。

基本文件属性包含一些与文件相关的信息,如创建时间、上次访问时间、上次修改时间、文件大小(以字节为单位),这些属性还告诉我们文件是否规则、文件是否为目录,或者文件是否是符号链接,或者文件是否不是常规文件、目录或符号链接。

用于获取基本文件属性的方法有:

Return TypeMethod Name And Description
FileTimecreationTime() – This method is used to get the creation time of the file.
FileTimelastAccessTime() – This method is used to get the last access time of the file
FileTimelastModifiedTime() – This method is used to get the last modified time of the file.
longsize() – This method is used to get the size of the file.
booleanisDirectory() – This method is used to check whether the file is a directory or not.
booleanisSymbolicLink() – This method is used to check whether the file is a symbolic link or not.
booleanisRegularFile() – This method is used to check whether the file is regular or not.
booleanisOther() – This method is used to check whether the file is something other than a regular file, or directory, or symbolic link.

下面是获取基本文件属性的Java程序:

Java
// Java Program to get the basic file attributes of the file
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.util.Date;
public class GFG {
    public static void main(String args[])
        throws IOException
    {
        // path of the file
        String path = "C:/Users/elavi/Desktop/GFG_File.txt";
  
        // creating a object of Path class
        Path file = Paths.get(path);
        
        // creating a object of BasicFileAttributes
        BasicFileAttributes attr = Files.readAttributes(
            file, BasicFileAttributes.class);
        System.out.println("creationTime Of File Is  = "
                           + attr.creationTime());
        System.out.println("lastAccessTime Of File Is  = "
                           + attr.lastAccessTime());
        System.out.println("lastModifiedTime Of File Is = "
                           + attr.lastModifiedTime());
  
        System.out.println("size Of File Is = "
                           + attr.size());
        System.out.println("isRegularFile Of File Is = "
                           + attr.isRegularFile());
        System.out.println("isDirectory Of File Is = "
                           + attr.isDirectory());
        System.out.println("isOther Of File Is = "
                           + attr.isOther());
  
        System.out.println("isSymbolicLink Of File Is  = "
                           + attr.isSymbolicLink());
    }
}


输出:

注意:以上程序只能在系统IDE上运行,不能在在线IDE上运行。