Java - File Specific Attribute Read

Introduction

You can read file attributes using a specific view object.

the getFileAttributeView() method of the Files class returns a specific attribute view.

It returns null if the file attribute view is not available.

The method declaration is as follows:

<V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options)

The following code reads all basic attributes for C:\myData\Main.java file using a basic view object:

// Get a Path object
Path path = Paths.get("C:\\myData\\Main.java");

// Get the basic view
BasicFileAttributeView bfv =
        Files.getFileAttributeView(path, BasicFileAttributeView.class);

// Read all basic attributes through the view
BasicFileAttributes bfa = bfv.readAttributes();

The following code uses the basic file attribute view to read and update basic file attributes.

Demo

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.Instant;

public class Main {
  public static void main(String[] args) {
    // Change the path to point to your file
    Path path = Paths.get("C:\\myData\\Main.java");

    try {/*from w w  w  .ja v a  2 s . c o m*/
      // Get the basic view
      BasicFileAttributeView bfv = Files.getFileAttributeView(path,
          BasicFileAttributeView.class);
      // Read all basic attributes through the view
      BasicFileAttributes bfa = bfv.readAttributes();

      // Print some basic attributes
      System.out.format("Size:%s bytes %n", bfa.size());
      System.out.format("Creation Time:%s %n", bfa.creationTime());
      System.out.format("Last Access Time:%s %n", bfa.lastAccessTime());

      // Update the create time to the current time
      FileTime newLastModifiedTime = null;
      FileTime newLastAccessTime = null;
      FileTime newCreateTime = FileTime.from(Instant.now());

      // A null for time means you do not want to update that time
      bfv.setTimes(newLastModifiedTime, newLastAccessTime, newCreateTime);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic