JavaSE: How to SET/GET your own Files and Directory Attributes

In the previous article “Determining Views Supported by a Particular File System” and see how to ask the file system store, and see supportability of a particular file attribute view.

We are going to explore in a nutshell, one of the most advanced and important files attribute views which is User-Defined File Attributes View.

Particularly, I am using this feature a lot in my exchanged files during integration between my systems, to hide my files meta-data and security related information from users and contents of the file. So the file content will be only regarding the content of the file only, no more irrelevant meta-data.

Therefore If you find that there are not enough built-in attributes for your needs or if you have some unique meta-data (meaningful to the file system) that you want to associate with a file, you can define your own attributes.

NIO.2 offers the user-defined file attributes view, extended attributes through the UserDefinedFileAttributeView interface. This facility allows you to associate to a file any attribute that you consider to be useful for your use cases.

Here you should know how to:

  1. Check User-Defined Attributes Supportability
  2. Operations on User-Defined Attributes as the following:
    1. Define a User Attribute.
    2. List User-Defined Attribute Names and Value Sizes.
    3. Get the Value of a User-Defined Attribute.
    4. Delete a File’s User-Defined Attribute.

Here is the class that has operations defined previously, also you need to use JDK 7+:

import static java.lang.System.err;
import static java.lang.System.out;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import static java.nio.file.Files.getFileStore;
import java.nio.file.Path;
import static java.nio.file.Paths.get;
import java.nio.file.attribute.UserDefinedFileAttributeView;
 
/**
 * GET/SET FILES METADATA THROUGH THE NEW JAVA.NIO.FILE.ATTRIBUTE API.
 *
 * @author mohamed_taman
 *
 * @see java.nio.file.attribute
 * @see java.nio.file.Files
 */
public class MetadataOperations {
 
    private static FileSystem fs = FileSystems.getDefault();
    private static Path path = get("C:", "workspace/NIO2", "resources", "TOC.txt");
 
    public static void main(String... args) {
 
       //User-Defined File Attributes View |
        userDefinedViewsOperations();
 
    }
 
    private static void userDefinedViewsOperations() {
 
        try {
             
            // Check User-Defined Attributes Supportability
 
            if (getFileStore(path)
                .supportsFileAttributeView(UserDefinedFileAttributeView.class)) {
                
                // 1- Define a User Attribute.
                 
                UserDefinedFileAttributeView udfav = Files.getFileAttributeView(path, 
                          UserDefinedFileAttributeView.class);
                 
                out.println("Attrs. before deletion. its size: " + udfav.list().size());
                 
                for (String name : udfav.list()) {
                    out.println(udfav.size(name) + " " + name);
                }
 
                int written = udfav.write("file.description", Charset.defaultCharset().
                        encode("This file contains private information about HOL2846!"));
 
                // 2- List User-Defined Attribute Names and Value Sizes.
                 
                for (String name : udfav.list()) {
                    out.println(udfav.size(name) + " " + name);
                }
 
                // 3- Get the Value of a User-Defined Attribute.
                  
                int size = udfav.size("file.description");
                ByteBuffer bb = ByteBuffer.allocateDirect(size);
                udfav.read("file.description", bb);
                bb.flip();
 
                out.println(Charset.defaultCharset().decode(bb).toString());
 
                /**
                 * Note: Using the UserDefinedFileAttributeView.size() method, 
                 * you can easily set the correct size of the buffer that represents 
                 * the value of the user-defined attribute.
                 * 
                 * Note: You can also read an attribute by using the getAttribute() method. 
                 * The value is returned as byte array (byte[]).
                 * 
                 */
                 
                 // 4- Delete a File’s User-Defined Attribute.
              
                out.println("Attrs. before deletion.");
                 
                for (String name : udfav.list()) {
                    out.println(udfav.size(name) + " " + name);
                }
 
                udfav.delete("file.description");
 
                out.println("Attrs. after deletion.");
                 
                for (String name : udfav.list()) {
                    out.println(udfav.size(name) + " " + name);
                }
 
            } else {
 
                out.println(path.toAbsolutePath().toString() + 
                         ", Doesn't support user defined attributes.");
            }
        } catch (Exception e) {
            err.println(e);
        }
    }
}

Resources

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


9 − two =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close