×

Java Programs

Java Practice

Java program to get the attributes of a file

In this java program, we are going to learn how to get and print the attributes of a file? Here, we are accessing the attributes like file creation time, last access time, last modified time, file key etc.
Submitted by IncludeHelp, on November 07, 2017

Given a file and we have to find its attributes using java program.

Following packages are using here, to implement this program,

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

There are following two important classes, which are using this program to get the file attributes,

  • BasicFileAttributeView
  • BasicFileAttributes

The method readAttributes() of BasicFileAttributeView is using to get the file attributes.

Program to get file attributes in java

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

public class BasicAttributeOfFile {
  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 = FileSystems.getDefault().getPath(A);

    // function is used to view file attribute.
    BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);
    BasicFileAttributes attributes = view.readAttributes();

    // all the attributes of the file.
    System.out.println("Creation Time: " + attributes.creationTime());
    System.out.println("Last Accessed Time: " + attributes.lastAccessTime());
    System.out.println("Last Modified Time: " + attributes.lastModifiedTime());
    System.out.println("File Key: " + attributes.fileKey());
    System.out.println("Directory: " + attributes.isDirectory());
    System.out.println("Other Type of File: " + attributes.isOther());
    System.out.println("Regular File: " + attributes.isRegularFile());
    System.out.println("Symbolic File: " + attributes.isSymbolicLink());
    System.out.println("Size: " + attributes.size());
  }
}

Output

Enter the file path : E:/JAVA
Creation Time: 2017-10-10T06:03:22.695314Z
Last Accessed Time: 2017-11-04T06:09:35.778029Z
Last Modified Time: 2017-11-04T06:09:35.778029Z
File Key: null
Directory: true
Other Type of File: false
Regular File: false
Symbolic File: false
Size: 4096

Java File Handling Programs »





Comments and Discussions!

Load comments ↻





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