is it possible to set custom metadata on files, using Java?

后端 未结 2 1289
陌清茗
陌清茗 2021-02-14 21:46

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 fil

2条回答
  •  终归单人心
    2021-02-14 22:46

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

提交回复
热议问题