How to Add Custom File Attributes

1 year ago by in How To, IO Tagged:

The Files class (Java Doc) added in Java 7 (Java Doc) provides an easy way to add and retrieve custom file’s attributes as shown in the following example.

package com.javacreed.examples.io;

import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserDefinedFileAttributeView;

public class Example {

  public static void main(final String[] args) throws Exception {
    final Path file = Paths.get(Example.class.getResource("/samples/example.txt").toURI()).toAbsolutePath();

    final UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);

    // The file attribute
    final String name = "com.javacreed.attr.1";
    final String value = "Custom Value 1";

    // Write the properties
    final byte[] bytes = value.getBytes("UTF-8");
    final ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
    writeBuffer.put(bytes);
    writeBuffer.flip();
    view.write(name, writeBuffer);

    // Read the property
    final ByteBuffer readBuffer = ByteBuffer.allocate(view.size(name));
    view.read(name, readBuffer);
    readBuffer.flip();
    final String valueFromAttributes = new String(readBuffer.array(), "UTF-8");
    System.out.println("File Attribute: " + valueFromAttributes);
  }
}

The above code can be downloaded from https://github.com/javacreed/how-to-add-custom-file-attributes.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

Leave a Comment