← 中文资源

简体中文版本

UserDefinedFileAttributeView 扩展属性

用 UserDefinedFileAttributeView 把来源、页数这类元数据挂在文件本体上:write 写入、list 列出、read 取回、delete 删除,不必另建索引表。

阅读英文原文

实现说明

真正干活的是类 AttachmentMetadata,其余都是接线。

使用要点

  • 直接运行文件,输出会带上标签,比如 view name:、stored:、source bytes:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「UserDefinedFileAttributeView 扩展属性」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 view name:、stored:、source bytes: 这类标签。

核心语句

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);

代码示例

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);
    }
}