Java - File Attribute View Availability Checking

Introduction

Not all file attribute views are supported on all platforms, except the basic view.

supportsFileAttributeView() method of the FileStore class tells whether a specific file attribute view is supported by a file store.

The method accepts the class reference of the type of the file attribute view.

It returns true if the specified file attribute view is supported; otherwise, it returns false.

The following code shows how to check for file attribute support:

Path path = get a path reference to a file store;

// Get the file store reference for the path
FileStore fs = Files.getFileStore(path);

// Check if POSIX file attribute is supported by the file store
boolean supported =    fs.supportsFileAttributeView(PosixFileAttributeView.class);
if (supported) {
        System.out.println("POSIX file attribute view is supported.");
}
else {
        System.out.println("POSIX file attribute view is not supported.");
}

The following code checks if a file store supports a file attribute view.

It checks for the file attribute support for the C: drive on Windows.

Demo

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.DosFileAttributeView;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.FileOwnerAttributeView;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.UserDefinedFileAttributeView;

public class Main {
  public static void main(String[] args) {
    // Use C: as the file store path on Windows
    Path path = Paths.get("C:");
    try {/*ww  w  .  jav a2  s.co m*/
      FileStore fs = Files.getFileStore(path);
      printDetails(fs, AclFileAttributeView.class);
      printDetails(fs, BasicFileAttributeView.class);
      printDetails(fs, DosFileAttributeView.class);
      printDetails(fs, FileOwnerAttributeView.class);
      printDetails(fs, PosixFileAttributeView.class);
      printDetails(fs, UserDefinedFileAttributeView.class);
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static void printDetails(FileStore fs,
      Class<? extends FileAttributeView> attribClass) {
    // Check if the file attribute view is supported
    boolean supported = fs.supportsFileAttributeView(attribClass);

    System.out.format("%s is supported: %s%n", attribClass.getSimpleName(),
        supported);
  }
}

Result

Related Topic