9

Is it possible to get and set custom metadata on File instances? I want to use the files that I process through my system as some kind of a very simple database, where every file should contain additional custom metadata, such as the email of the sender, some timestamps, etc.

It is for an internal system, so security is not an issue.

Preslav Rachev
  • 3,983
  • 6
  • 39
  • 63
  • 1
    For a similar requirement I created an additional meta data file for every file, i.e. a file named `report.pdf` had a `report.pdf.meta` file which contained the meta data. Not as fancy as using extended attributes, but it worked. – Daniel Rikowski Apr 09 '13 at 16:39

2 Answers2

8

In java 7 you can do this using the Path class and UserDefinedFileAttributeView.

Here is the example taken from there:

A file's MIME type can be stored as a user-defined attribute by using this code snippet:

Path file = ...;
UserDefinedFileAttributeView view = Files
    .getFileAttributeView(file, UserDefinedFileAttributeView.class);
view.write("user.mimetype",
           Charset.defaultCharset().encode("text/html");

To read the MIME type attribute, you would use this code snippet:

Path file = ...;
UserDefinedFileAttributeView view = Files
.getFileAttributeView(file,UserDefinedFileAttributeView.class);
String name = "user.mimetype";
ByteBuffer buf = ByteBuffer.allocate(view.size(name));
view.read(name, buf);
buf.flip();
String value = Charset.defaultCharset().decode(buf).toString();
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • What happens if you use `UserDefinedFileAttributeView` with a file system that doesn't natively support POSIX extended attributes, i.e. FAT? Is it emulated somehow? – Daniel Rikowski Apr 09 '13 at 16:29
  • I couldn't find a comprehensive list, [this](http://stackoverflow.com/questions/15319586/what-file-sytems-support-java-userdefinedfileattributeview) answer lists a few file systems. I guess the only way to find out is it try it on FAT and see what happens. – Boris the Spider Apr 09 '13 at 16:32
2

You should always check if the filesystem supports UserDefinedFileAttributeView for the specific file you want to set You can simply invoke this

Files.getFileStore(Paths.get(path_to_file))).supportsFileAttributeView(UserDefinedFileAttributeView.class);

From my experience, the UserDefinedFileAttributeView is not supported in FAT* and HFS+ (for MAC) filesystems

pkran
  • 181
  • 1
  • 7