UserDefinedFileAttributeView Stores Custom Metadata

Attach named user attributes to a file with UserDefinedFileAttributeView, read them back as bytes, and remove them with delete when superseded.

JavaConfig Management

Code

snippet
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.UserDefinedFileAttributeView;

public class AttachmentMetadata {

    public static void main(String[] args) throws IOException {
        Path doc = Files.createTempFile("invoice-", ".pdf");
        Files.writeString(doc, "%PDF-1.7 mock payload");

        // user 视图:把来源追踪这类元数据直接挂在文件上,而不是另建数据库行
        UserDefinedFileAttributeView attrs =
                Files.getFileAttributeView(doc, UserDefinedFileAttributeView.class);
        System.out.println("view name: " + attrs.name());

        attrs.write("source", ByteBuffer.wrap("procurement-portal".getBytes(StandardCharsets.UTF_8)));
        attrs.write("pages", ByteBuffer.wrap("12".getBytes(StandardCharsets.UTF_8)));

        System.out.println("stored: " + attrs.list());
        System.out.println("source bytes: " + attrs.size("source"));

        ByteBuffer out = ByteBuffer.allocate(attrs.size("source"));
        attrs.read("source", out);
        System.out.println("read back: " + new String(out.array(), StandardCharsets.UTF_8));

        attrs.delete("pages");
        System.out.println("after delete: " + attrs.list());

        Files.deleteIfExists(doc);
    }
}

What the code does

UserDefinedFileAttributeView Stores Custom Metadata keeps everything in the class AttachmentMetadata.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The run emits 5 labeled sections — view name:, stored:, source bytes:, read back:, after delete: — one per step.

Statements that matter most here

attrs.write("source", ByteBuffer.wrap("procurement-portal".getBytes(StandardCharsets.UTF_8)));
attrs.write("pages", ByteBuffer.wrap("12".getBytes(StandardCharsets.UTF_8)));
Files.getFileAttributeView(doc, UserDefinedFileAttributeView.class);

Interactive Tools for This Topic

FAQ

What does UserDefinedFileAttributeView Stores Custom Metadata print when run?
Running the file directly is enough — expect labeled output lines such as `view name:`, `stored:`, `source bytes:`.