Sunday 9 October 2016

Accessing meta data of a file (All attributes of file)

While dealing with files, you may need to know some of the information like size of the file, whether file is directory, file is regular file, is file hidden etc., All this information named as file meta data, it describes about the file. A file meta data is represented by set of attributes.

How to get (or) set attribute of a file?
The Files class includes methods that can be used to obtain a single attribute of a file, or to set an attribute.

Following table summarizes some of the methods of Files class, that gives the file metadata.

Method
Description
public static Object  getAttribute(Path path, String attribute, LinkOption... options)
Reads the value of a file attribute.

Ex:
int uid = (Integer)Files.getAttribute(path, "unix:uid");
public static FileTime getLastModifiedTime(Path path, LinkOption... options)throws IOException
Returns a file's last modified time.
public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException
Returns the owner of a file.
public static Set<PosixFilePermission> getPosixFilePermissions(Path path,LinkOption... options)throws IOException
Returns a file's POSIX file permissions.
public static boolean isDirectory(Path path, LinkOption... options)
true if the file is a directory; false if the file does not exist, is not a directory,
public static boolean isRegularFile(Path path, LinkOption... options)
Returns true if the file is a regular file; false if the file does not exist, is not a regular file, or it cannot be determined if the file is a regular file or not.
public static FileTime getLastModifiedTime(Path path, LinkOption... options)throws IOException
Returns a file's last modified time.
public static Path setLastModifiedTime(Path path, FileTime time)throws IOException
Updates a file's last modified time attribute.
public static long size(Path path)throws IOException
Returns the size of a file in bytes.
public static boolean isExecutable(Path path)
Return true if the file exists and is executable; false if the file does not exist, execute access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined
public static boolean isHidden(Path path)throws IOException
Return true if the file is considered hidden.
public static boolean isReadable(Path path)
Return true if the file exists and is readable; false if the file does not exist, read access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined
public static boolean isWritable(Path path)
Return true if the file exists and is writable; false if the file does not exist, write access would be denied because the Java virtual machine has insufficient privileges, or access cannot be determined
public static Path setAttribute(Path path, String attribute,Object value, LinkOption... options) throws IOException
Sets the value of a file attribute.

Ex:
Files.setAttribute(path, "dos:hidden", true);
public static Path setOwner(Path path, UserPrincipal owner)throws IOException
Updates the file owner.
public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms)throws IOException
Sets a file's POSIX permissions.

Note
LinkOption is used to handle symbolic links. By default, symbolic links are followed and the file attribute of the final target of the link is read. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.UserPrincipal;

public class FileMetaDataDemo {

 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  boolean isDirectory = Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS);
  FileTime lastModifiedTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
  UserPrincipal owner = Files.getOwner(path, LinkOption.NOFOLLOW_LINKS);
  boolean isRegularFile = Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS);
  long size = Files.size(path);
  boolean isExecutable = Files.isExecutable(path);
  boolean isHidden = Files.isHidden(path);
  boolean isReadable = Files.isReadable(path);
  boolean isWritable = Files.isWritable(path);

  System.out.println("Is Directory : " + isDirectory);
  System.out.println("lastModifiedTime : " + lastModifiedTime);
  System.out.println("owner : " + owner);
  System.out.println("isRegularFile : " + isRegularFile);
  System.out.println("size of the fie (in bytes) : " + size);
  System.out.println("isExecutable : " + isExecutable);
  System.out.println("isHidden : " + isHidden);
  System.out.println("isReadable : " + isReadable);
  System.out.println("isWritable : " + isWritable);

 }
}

Output
Is Directory : false
lastModifiedTime : 2016-09-25T03:48:37.502272Z
owner : GLOBAL\Krishna (User)
isRegularFile : true
size of the fie (in bytes) : 18667
isExecutable : true
isHidden : false
isReadable : true
isWritable : true

Accessing multiple file attributes at a time
Suppose you want to access more than one file attribute at a time, instead of using the methods that gives one attribute at a time, use ‘readAttributes’ method, that fetch multiple attributes in one bulk operation. Following table summarizes the readAttributes method.

Method
Description
public static <A extends BasicFileAttributes> A readAttributes(Path path,Class<A> type, LinkOption... options)throws IOException
Reads a file's attributes as a bulk operation. The type parameter is the type of the attributes required and this method returns an instance of that type if supported. Type can be BasicFileAttributes, DosFileAttributes, PosixFileAttributes (or) any classes that implement these interfaces.
public static Map<String,Object> readAttributes(Path path, String attributes,LinkOption... options)throws IOException
Reads a set of file attributes as a bulk operation.
The attributes parameter identifies the attributes to be read and takes the form:

[view-name:]attribute-list.

Following table summarizes the format of attributes argument.

Example
Description
"*"
Read all basic-file-attributes.
"size,lastModifiedTime,lastAccessTime"
Reads the file size, last modified time, and last access time attributes.

"posix:*"
Read all POSIX-file-attributes.
"posix:permissions,owner,size"
Reads the POSX file permissions, owner, and file size.



import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Map;

public class FileMetaDataDemoBulkRead {
 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  Map<String, Object> metaData = Files.readAttributes(path, "size,lastModifiedTime,lastAccessTime",
    LinkOption.NOFOLLOW_LINKS);

  for (String attribute : metaData.keySet()) {
   System.out.println(attribute + " : " + metaData.get(attribute));
  }
 }

}

Output
lastAccessTime : 2016-09-25T03:48:35.891766Z
lastModifiedTime : 2016-09-25T03:48:37.502272Z
size : 18667

To make the things simpler, Java divides the attributes of the file into different views. A view maps to a particular file system implementation, such as POSIX or DOS, or to a common functionality, such as file ownership.

Following are the different types of views supported by Java.

AclFileAttributeView,
BasicFileAttributeView,
DosFileAttributeView,
FileAttributeView,
FileOwnerAttributeView,
FileStoreAttributeView,
PosixFileAttributeView,
UserDefinedFileAttributeView

View
Description
AclFileAttributeView
Supports reading or updating a file's Access Control Lists (ACL) or file owner attributes.
BasicFileAttributeView
A file attribute view that provides a view of a basic set of file attributes common to many file systems, like last modified time, accessed time etc.,
DosFileAttributeView
A file attribute view that provides a view of the legacy "DOS" file attributes like hidden, readonly etc.,
FileAttributeView
An attribute view that is a read-only or updatable view of non-opaque values associated with a file in a filesystem. Interfaces AclFileAttributeView, BasicFileAttributeView, DosFileAttributeView, FileOwnerAttributeView, PosixFileAttributeView, UserDefinedFileAttributeView extend this interface.
FileOwnerAttributeView
A file attribute view that supports reading or updating the owner of a file.
FileStoreAttributeView
An attribute view that is a read-only or updatable view of the attributes of a FileStore.
PosixFileAttributeView
A file attribute view that provides a view of the file attributes commonly associated with files on file systems used by operating systems that implement the Portable Operating System Interface (POSIX) family of standards.
UserDefinedFileAttributeView

A file attribute view that provides a view of a file's user-defined attributes, sometimes known as extended attributes.
                                   
Files class provide 'readAttributes' method to access all these views. Following section explains each view separately.

Accessing basic file attributes of file
By using following statement, you can get the basic file attributes.


BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

public class FileMetaDataDemoBulkRead {
 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);

  System.out.println("creationTime: " + attr.creationTime());
  System.out.println("lastAccessTime: " + attr.lastAccessTime());
  System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

  System.out.println("isDirectory: " + attr.isDirectory());
  System.out.println("isOther: " + attr.isOther());
  System.out.println("isRegularFile: " + attr.isRegularFile());
  System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
  System.out.println("size: " + attr.size());
 }

}


Output
creationTime: 2016-09-24T05:02:03.661284Z
lastAccessTime: 2016-09-25T03:48:35.891766Z
lastModifiedTime: 2016-09-25T03:48:37.502272Z
isDirectory: false
isOther: false
isRegularFile: true
isSymbolicLink: false
size: 18667

DOS File Attributes
Following statements are used to get DosFileAttributes.

DosFileAttributes attr = Files.readAttributes(path, DosFileAttributes.class);
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.DosFileAttributes;

public class FileMetaDataDemoBulkRead {
 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  try {
   DosFileAttributes attr = Files.readAttributes(path, DosFileAttributes.class);
   System.out.println("isReadOnly is " + attr.isReadOnly());
   System.out.println("isHidden is " + attr.isHidden());
   System.out.println("isArchive is " + attr.isArchive());
   System.out.println("isSystem is " + attr.isSystem());
  } catch (UnsupportedOperationException x) {
   System.err.println("DOS file" + " attributes not supported:" + x);
  }
 }

}

Output
isReadOnly is false
isHidden is false
isArchive is true
isSystem is false

POSIX File Permissions
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;

public class FileMetaDataDemoBulkRead {
 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  try {
   PosixFileAttributes attr = Files.readAttributes(path, PosixFileAttributes.class);
   System.out.format("%s %s %s%n", attr.owner().getName(), attr.group().getName(),
     PosixFilePermissions.toString(attr.permissions()));
  } catch (Exception e) {
   System.out.println(e);
  }

 }

}

Working with User defined attributes
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.List;

public class FileMetaDataDemoBulkRead {
 public static void main(String args[]) throws IOException {
  String filePath = "C:\\Users\\Documents\\Study\\Miscellaneous\\Proxy.docx";
  Path path = new File(filePath).toPath();
  printMetadata(path);
 }

 private static void printMetadata(Path path) throws IOException {
  UserDefinedFileAttributeView userDefinedFAView = Files.getFileAttributeView(path,
    UserDefinedFileAttributeView.class);
  List<String> attributeList = userDefinedFAView.list();
  System.out.println("User Defined Attribute List Size Before Adding: " + attributeList.size());

  // set user define attribute
  userDefinedFAView.write("typeOfFile", Charset.defaultCharset().encode("personal"));

  attributeList = userDefinedFAView.list();
  if (attributeList.size() > 0) {
   for (String attName : attributeList) {
    ByteBuffer attValue = ByteBuffer.allocate(userDefinedFAView.size(attName));
    userDefinedFAView.read(attName, attValue);
    attValue.flip();
    System.out.println("User Defined Attribute Name: " + attName);
    System.out.println(
      "User Defined Attribute Value: " + Charset.defaultCharset().decode(attValue).toString());
   }
  } else {
   System.out.println(
     "User define attribute count should be at least 1" + " as we have set an attribute just now!");
  }

  System.out.println("User Defined Attribute List Size After setting: " + attributeList.size());

  userDefinedFAView.delete("typeOfFile");

  attributeList = userDefinedFAView.list();
  System.out.println("User Defined Attribute List Size After Deleting: " + attributeList.size());

 }

}

Output
User Defined Attribute List Size Before Adding: 0
User Defined Attribute Name: typeOfFile
User Defined Attribute Value: personal
User Defined Attribute List Size After setting: 1
User Defined Attribute List Size After Deleting: 0












No comments:

Post a Comment