Java NIO.2 File Attributes
This primer on Java's File I/O API will familiarize you with files' attributes and the views you can use to manage and alter them.
Join the DZone community and get the full member experience.
Join For FreeJava NIO has improved a lot ever since it was introduced. Especially from Java 7 onwards, there have been lots of improvements to the File I/O API. Today, we're going to go over some of those improvements in detail.
Prior to Java 7, there were much fewer of attributes available to File objects in Java. Because of that, it was very difficult to query a file for its attributes in great detail. If you wanted advanced querying capabilities, then you needed to implement it yourself. For example, you could not know when a file was last accessed prior to Java 7. But with the help of NIO File attributes, Java advanced its capabilities in this area.
Basic Attributes
Every file has the following attributes in any operating system:
File type
File size
Created time
Owner of the file
Last time modified
Last time accessed
Hidden
System file
Regular file
isDirectory
FileAttributeView
FileAttributeView is a super interface with the following sub-interfaces.
BasicFileAttributeView
DosFileAttributeView
PosixFileAttributeView
UserDefinedFileAttributeView
AclFileAttributeView
FileOwnerAttributeView
These interfaces provide the implementation for the file attributes explained in the beginning.
Using the Interfaces
Since all of the above are interfaces, you cannot use them directly. The proper usage of these interfaces is as follows:
Path path = FileSystems.getDefault().getPath("c:/test", "somefile.txt");
BasicFileAttributeView basicView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
But let's investigate the attribute views in more details=.
BasicFileAttributeView
This is the basic file attribute view that will be used to inquire the following:
- LastAccessedTime
- LastModifiedTime
- CreationTime
basicView.readAttributes().lastAccessTime().toMillis();; // will return the last time the file was read.
basicView.readAttributes().lastModifiedTime().toMillis(); // will return the last time the file was changed.
basicView.readAttributes().creationTime().toMillis(); // will return the creation time.
DosFileAttributeView
DOS (Disk Operating System) is a legacy Operating System. DOS has a couple of attributes for File objects.
Hidden: Checks whether the file is visible or not.
Readonly: Checks the readOnly status.
System: Checks whether the file is a System. For example, almost all files in the System32 folder are the system files in Windows.
Archive: This is used to tell backup programs that the file can be archived.
In order to set the above attributes, we need to call the following:
DosFileAttributeView dosView = Files.getFileAttributeView(path,DosFileAttributeView.class);
dosView.setHidden(true);
dosView.setReadOnly(true);
dosView.setSystem(true);
dosView.setArchive(true);
PosixFileAttributeView
Basically, an operating system that implements POSIX has got read, write, and group permissions. UNIX, Linux, and Windows are such operating systems. This file attribute view provides read and write access to these attributes.
For example, in order to get an owner and permissions of a file, we can do the following:
PosixFileAttributeView posixView = Files.getFileAttributeView(path,PosixFileAttributeView.class);
PosixFileAttributes attrs = posixView.readAttributes();
System.out.println(“ file owner and permissions “ + attrs.owner().getName() +” “ + PosixFilePermissions.toString(attrs.permissions()));
This file attribute view can be used where dynamic access to the attributes is required.
AclFileAttributeView
This file attribute extends FileOwnerAttributeView, which supports reading and updating a file’s access control lists. ACL is actually used to provide access control to objects. For example, if an object has an ACL like {Alice:read, write, Bob:read}, then this would give Alice read and write permission, whereas Bob would get only read permissions.
Let’s us look at a use case. Bob has admin privileges to delete files in the OS. So Bob can delete the irrelevant files uploaded by a user. In a web application, this can be achieved very easily by using this attribute view.
AclFileAttributeView aclView = new Files.getFileAttributeView(path, AclFileAttributeView.class);
UserPrincipal bob = FileSystems.getDefault().getUserPrincipalLookupService().getUserPrincipalByName(“bob”) // getting ‘bob’ user principal.
Now we need to create an ‘ACL entry’ for ‘bob’ like this:
AclEntry entry = AclEntry.newBuilder().setType(AclEntryType.ALLOW).setPrincipal(bob).setPermissions(AclEntryPermission.DELETE, AclEntryPermission.READ, AclEntryPermission.READ_DATA);
// gets all the entries
List<AclEntry> aclEntries = view.getAcl();
aclEntries.clear();
// add permission
aclEntries.add(entry);
Now this operation will set DELETE permission to user ‘bob’ to delete the file named ‘somefile.txt’ through the application.
FileOwnerAttributeView
This attribute view, as the name suggests, is going to change the owner of the file. With the help of the following code, we can do this:
FileOwnerAttributeView ownerView = new Files.getFileAttributeView(path, FileOwnerAttributeView.class);
Let's assume that the current owner of the file is ‘bob’. We will change this to ‘Alice’.
ownerView.setOwner(“Alice”);
UserDefinedFileAttributeView
This attribute will help create user-defined attributes for a file. A straightforward use case is to change the file’s user-defined attribute called ‘mime type’.
UserDefinedFileAttributeView view = FIles.getFileAttributeView(path, UserDefinedFileAttributeView.class);
String userDefinedAttribute = “user.mimetype”;
view.write(userDefinedAttribute, Charset.defaultCharset().encode("text/html"));
The last line sets the file’s user defined attribute called ‘user.mimetype’ to “text/html”.
Summary
We explained the attribute views associated with File objects in the NIO.2 package. These file attribute views provide standard implementations for managing file attributes. With the help of these attribute views, common issues related to file attributes can be solved extremely easily and can guarantee a cross-platform solution instead of re-inventing the wheel.
Opinions expressed by DZone contributors are their own.
Comments