Java - File Attributes Reading and Updating

Introduction

You may need to work with one or more attributes of a file at a time.

The following Files class static methods can read and update a file attribute using the attribute name as a string:

Object getAttribute(Path path, String attribute, LinkOption... options)
Path setAttribute(Path path, String attribute, Object value, LinkOption... options)

To read or update multiple attributes of a file, work with a specific file attribute view.

You have to work with two interfaces named as XxxAttributes and XxxAttributeView.

For the basic file attributes, you have the BasicFileAttributes and BasicFileAtrributeView interfaces.

The XxxAttributes lets you read the attributes.

The XxxAttributeView lets you read as well as update the attributes.

The following two methods from Files class can read the file attributes in a bulk.

<A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
Map<String,Object> readAttributes(Path path, String attributes, LinkOption... options)

The following code shows how to read the 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.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class Main {
  public static void main(String[] args) throws IOException {
    // Create the Path object representing the path of the file
    Path path = Paths.get("C:\\myData\\Main.java");

    // Read the basic file attributes
    BasicFileAttributes bfa = Files.readAttributes(path,
        BasicFileAttributes.class);

    // Get the last modified time
    FileTime lastModifiedTime = bfa.lastModifiedTime();

    // Get the size of the file
    long size = bfa.size();
  }//  www  .j  a v  a 2 s .c o  m
}

Result

The second readAttributes() method returns all or some of the attributes of a specific type.

Related Topic