Home  >  Java 7

Example of BasicFileAttributes in Java NIO

By Arvind Rai, December 12, 2013
java.nio.file.attribute.BasicFileAttributes is an interface and has been introduced in JDK 7. BasicFileAttributes is the part of java NIO 2. BasicFileAttributes provides basic file attributes. To get the instance of BasicFileAttributes, Files.readAttributes() is used. BasicFileAttributes can provide last access time, last modified time, creation time etc.

Files.readAttributes() in Java NIO

Reads the attribute of a file and initializes the BasicFileAttributes. We need to provide path and BasicFileAttributes class. It returns BasicFileAttributes object to access the file time.

BasicFileAttributes.creationTime() in Java NIO

We need to pass the file path, and it will return FileTime and we get the file creation time.

BasicFileAttributes.lastAccessTime() in Java NIO

By this method we get the last access time of a file as FileTime object.

BasicFileAttributes.lastModifiedTime() in Java NIO

It returns the FileTime Object which is will be last modified time of a file.
BasicFileAttributesExample.java
package com.concretepage.io.file.attribute;
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 BasicFileAttributesExample {
	public static void main(String[] args) throws IOException {
		 Path file = Paths.get("D:/cp","BasicFileAttributesExample.java");
		 BasicFileAttributes basicAttr = Files.readAttributes(file, BasicFileAttributes.class);
		 FileTime creationTime = basicAttr.creationTime();
		 System.out.println(creationTime);
		 FileTime lastAccessTime = basicAttr.lastAccessTime();
		 System.out.println(lastAccessTime);
		 FileTime lastModifiedTime = basicAttr.lastModifiedTime();
		 System.out.println(lastModifiedTime);
	}
}
 

Output
2013-12-11T09:06:01.137677Z
2013-12-11T09:06:01.137677Z
2013-12-11T09:05:42.341918Z
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us